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

时间:2012-04-05 00:11:37

标签: c# winforms string replace char

您好我正在尝试从字符串中删除所有特定字符。我一直在使用String.Replace,但它没有,我不知道为什么。这是我目前的代码。

    public string color;
    public string Gamertag2;
    private void imcbxColor_SelectedIndexChanged(object sender, EventArgs e)
    {
        uint num;
        XboxManager manager = new XboxManagerClass();
        XboxConsole console = manager.OpenConsole(cbxConsole.Text);
        byte[] Gamertag = new byte[32];
        console.DebugTarget.GetMemory(0x8394a25c, 32, Gamertag, out num);
        Gamertag2 = Encoding.ASCII.GetString(Gamertag);
        if (Gamertag2.Contains("^"))
        {
            Gamertag2.Replace("^" + 1, "");
        }
        color = "^" + imcbxColor.SelectedIndex.ToString() + Gamertag2;
        byte[] gtColor = Encoding.ASCII.GetBytes(color);
        Array.Resize<byte>(ref gtColor, gtColor.Length + 1);
        console.DebugTarget.SetMemory(0x8394a25c, (uint)gtColor.Length, gtColor, out num);
    }

它基本上从我的Xbox 360中检索字符串的字节值,然后将其转换为字符串形式。但我希望它删除所有“^”String.Replace的实例似乎不起作用。它什么都没做。它只是留下以前的字符串。任何人都可以向我解释为什么会这样做?

4 个答案:

答案 0 :(得分:62)

您必须将String.Replace的返回值分配给原始字符串实例:

因此而不是(不需要Contains check)

if (Gamertag2.Contains("^"))
{
    Gamertag2.Replace("^" + 1, "");
}

就是这个(什么是神秘的+1?):

Gamertag2 = Gamertag2.Replace("^", "");

答案 1 :(得分:12)

两件事:

1)C#字符串是不可变的。你需要这样做:

Gamertag2 = Gamertag2.Replace("^" + 1, "");

2)"^" + 1?你为什么做这个?你基本上是在说Gamertag2.Replace("^1", "");,我确信这不是你想要的。

答案 2 :(得分:2)

就像攀岩说的那样,你的问题肯定是

Gamertag2.Replace("^"+1,"");

该行只会删除&#34; ^ 1&#34;的实例。从你的字符串。如果你想删除&#34; ^&#34;的所有实例,你想要的是:

Gamertag2.Replace("^","");

答案 3 :(得分:0)

我知道这个线程很旧,而且我的解决方案可能效率很低,但它替换了所有出现的字符串。发现如果我正在寻找“\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"));