如何从字符串中删除特定字符的所有实例
本文关键字:字符 实例 字符串 删除 | 更新日期: 2023-09-27 18:29:58
我正在尝试从字符串中删除所有特定字符。我一直在使用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", "");
,我相信这不是你想要的。
就像climbage说的,你的问题肯定是
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"));