C# 如何用空字符串替换出现的“-”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/894905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 08:44:59  来源:igfitidea点击:

How to replace occurrences of "-" with an empty string?

c#string

提问by Gold

I have this string: "123-456-7"

我有这个字符串:“123-456-7”

I need to get this string: "1234567"

我需要得到这个字符串:“1234567”

How I can replace occurrences of "-" with an empty string?

如何用空字符串替换出现的“-”?

采纳答案by Sean Bright

string r = "123-456-7";
r = r.Replace("-", "");

回答by Jose Basilio

This should do the trick:

这应该可以解决问题:

String st = "123-456-7".Replace("-","");

回答by abelenky

To be clear, you want to replace each hyphen (-) with blank/nothing. If you replaced it with backspace, it would erase the character before it!

需要明确的是,您希望将每个连字符 (-) 替换为空白/无。如果你用退格键替换它,它会擦除​​它之前的字符!

That would lead to: 123-456-7 ==> 12457

这将导致: 123-456-7 ==> 12457

Sean Bright has the right answer.

肖恩·布莱特给出了正确的答案。

回答by Syed Tayyab Ali

String.Replace Method (String, String)

String.Replace 方法(字符串,字符串)

in your case it would be

在你的情况下,它会是

string str = "123-456-7";
string tempstr = str.Replace("-","");

回答by SO User

string r = "123-456-7".Replace("-", String.Empty);

For .Net 1.0 String.Empty will not take additional space on the heap but "" requires storage on the heap and its address on the stack resulting in more assembly code. Hence String.Empty is faster than "".

对于 .Net 1.0 String.Empty 不会在堆上占用额外的空间,但 "" 需要在堆上的存储及其在堆栈上的地址,从而导致更多的汇编代码。因此 String.Empty 比 "" 快。

Also String.Empty mean no typo errors.

String.Empty 也意味着没有拼写错误。

Check the What is the difference between String.Empty and “”link.

检查String.Empty 和“”之间的区别什么链接。

回答by Darshana

Use String.Empty or null instead of "" since "" will create an object in the memory for each occurrences while others will reuse the same object.

使用 String.Empty 或 null 而不是 "" 因为 "" 将为每次出现在内存中创建一个对象,而其他人将重用相同的对象。