我正在尝试从字符串中删除所有特定字符。我一直在使用String.Replace
,但它什么也没做,我不知道为什么。这是我当前的代码:
if (Gamertag2.Contains("^"))
{
Gamertag2.Replace("^" + 1, "");
}
这只是让字符串保持原样。谁能向我解释为什么?
您必须将返回值分配给String.Replace
原始字符串实例:
因此而不是(不需要Contains check)
if (Gamertag2.Contains("^"))
{
Gamertag2.Replace("^" + 1, "");
}
只是这个(那是什么神秘的+1
?):
Gamertag2 = Gamertag2.Replace("^", "");
两件事情:
1) C# 字符串是不可变的。你需要这样做:
Gamertag2 = Gamertag2.Replace("^" + 1, "");
2) "^" + 1
? 你为什么做这个?您基本上是在说Gamertag2.Replace("^1", "");
我确定这不是您想要的。
就像攀登说的,你的问题肯定是
Gamertag2.Replace("^"+1,"");
该行只会从您的字符串中删除“^1”的实例。如果要删除“^”的所有实例,您想要的是:
Gamertag2.Replace("^","");
我知道这个线程很旧,而且我的解决方案可能效率极低,但它替换了所有出现的字符串。发现如果我正在寻找 "\r\n\r\n\r\n" 以替换为 "\r\n\r\n" 单个 Replace() 并不能全部捕获。
为此:
do // First get rid of spaces like " \r"
{
str = str.Replace(" \r","\r")
} while (str.Cointains(" \r"));
do // Then remove the CrLf's in surplus.
{
str = str.Replace("\r\n\r\n\r\n","\r\n\r\n")
} while (str.Cointains("\r\n\r\n\r\n"));