如何从一个字符串中删除特定字符的所有实例(how to remove all instances o

2019-07-28 20:15发布

你好,我想从一个字符串中删除所有特定字符的。 我一直在使用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似乎并没有工作。 它也绝对没有什么。 它只是离开琴弦,因为它以前。 任何人都可以请向我解释,为什么它这样做?

Answer 1:

您必须的返回值赋给String.Replace你原来的字符串实例:

因此,而不是(无需对Contains check)

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

只是这(那是什么神秘+1 ?):

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


Answer 2:

两件事情:

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

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

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



Answer 3:

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

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

该行只会从你的字符串中删除的“^ 1”的实例。 如果你想删除的“^”任何情况下,你想要的是:

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


文章来源: how to remove all instances of a specific character from a string