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

Ian*_*erg 31 c# string replace char winforms

您好我试图从字符串中删除所有特定字符.我一直在使用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);
    }
Run Code Online (Sandbox Code Playgroud)

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

Tim*_*ter 65

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

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

if (Gamertag2.Contains("^"))
{
    Gamertag2.Replace("^" + 1, "");
}
Run Code Online (Sandbox Code Playgroud)

就是这个(什么是神秘主义者+1?):

Gamertag2 = Gamertag2.Replace("^", "");
Run Code Online (Sandbox Code Playgroud)

  • @Ian - 我不相信.除非你没有告诉我们什么,"Gamertag2 = Gamertag2.Replace("^","");`肯定会删除"^"的任何实例.在`String.Replace`之后设置一个断点,看它是否从`Gamertag2`中删除了"^". (4认同)
  • 字符串是不可变的 - 这意味着你需要将它分配给某个东西..Replace将返回一个新字符串. (3认同)

Mik*_*ark 12

两件事情:

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

Gamertag2 = Gamertag2.Replace("^" + 1, "");
Run Code Online (Sandbox Code Playgroud)

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