繁体   English   中英

如何从字符串中删除特定字符的所有实例?

[英]How to remove all instances of a specific character from a string?

我正在尝试从字符串中删除所有特定字符。 我一直在使用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", ""); 我确定这不是您想要的。

就像climage说的,你的问题肯定是

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"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM