how to remove all instances of a specific characte

2019-03-23 03:35发布

问题:

Hello I am trying to remove all of a specific character from a string. I have been using String.Replace, BUT IT DOES NOTHING and I don't know why. This is my current code.

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

It basically retrieves the byte value of a string from my Xbox 360, then converts it into string form. but I want it to remove all instances of "^" String.Replace doesn't seem to work. It does absolutely nothing. It just leaves the string as it was before. Can anyone please explain to me as to why it does this?

回答1:

You must assign the return value of String.Replace to your original string instance:

hence instead of(no need for the Contains check)

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

just this(what's that mystic +1?):

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


回答2:

Two things:

1) C# Strings are immutable. You'll need to do this :

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

2) "^" + 1? Why are you doing this? You are basically saying Gamertag2.Replace("^1", ""); which I'm sure is not what you want.



回答3:

Like climbage said, your problem is definitely

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

That line will only remove instances of "^1" from your string. If you want to remove all instances of "^", what you want is:

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