how to remove all instances of a specific character from a string

Go To StackoverFlow.com

28

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?

2012-04-05 00:11
by Ian Lundberg
Did you try Regular Expression - Sandeep 2012-04-05 02:16
@Sandeep Regular Expressions would overcomplicate a straightforward issue - Amicable 2014-04-17 12:53


59

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("^", "");
2012-04-05 00:15
by Rango
@Ian - I'm not convinced. Unless there's something you're not telling us, Gamertag2 = Gamertag2.Replace("^", ""); will definitely remove any instance of "^". Set a break point after the String.Replace and see if it removes "^" from Gamertag2 - Mike Park 2012-04-05 02:37
a string is immutable - which means you need to assign it to something. .Replace will return a new string - Shumii 2015-01-13 15:40


12

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.

2012-04-05 00:14
by Mike Park


2

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("^","");
2014-08-12 18:50
by stackPusher
Ads