C# 如何从字符串中删除特定字符的所有实例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10021036/
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
How to remove all instances of a specific character from a string?
提问by Ian Lundberg
I am trying to remove all of a specific character from a string. I have been using String.Replace, but it does nothing, and I don't know why. This is my current code:
我正在尝试从字符串中删除所有特定字符。我一直在使用String.Replace,但它什么也没做,我不知道为什么。这是我当前的代码:
if (Gamertag2.Contains("^"))
{
Gamertag2.Replace("^" + 1, "");
}
This just leaves the string as it was before. Can anyone please explain to me as to why?
这只是使字符串保持原样。任何人都可以向我解释为什么吗?
采纳答案by Tim Schmelter
You must assign the return value of String.Replaceto your original string instance:
您必须将 的返回值分配给String.Replace原始字符串实例:
hence instead of(no need for the Contains check)
因此而不是(不需要 Contains check)
if (Gamertag2.Contains("^"))
{
Gamertag2.Replace("^" + 1, "");
}
just this(what's that mystic +1?):
只是这个(那是什么神秘的+1?):
Gamertag2 = Gamertag2.Replace("^", "");
回答by Mike Park
Two things:
两件事情:
1) C# Strings are immutable. You'll need to do this :
1) C# 字符串是不可变的。你需要这样做:
Gamertag2 = Gamertag2.Replace("^" + 1, "");
2) "^" + 1? Why are you doing this? You are basically saying Gamertag2.Replace("^1", "");which I'm sure is not what you want.
2) "^" + 1? 你为什么做这个?您基本上是在说Gamertag2.Replace("^1", "");我确定这不是您想要的。
回答by stackPusher
Like climbage said, your problem is definitely
就像攀登说的,你的问题肯定是
Gamertag2.Replace("^"+1,"");
That line will only remove instances of "^1" from your string. If you want to remove all instances of "^", what you want is:
该行只会从您的字符串中删除“^1”的实例。如果要删除“^”的所有实例,您需要的是:
Gamertag2.Replace("^","");

