How to remove all instances of a specific character from a string?

后端 未结 3 1339
抹茶落季
抹茶落季 2021-02-06 21:32

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 co

相关标签:
3条回答
  • 2021-02-06 22:08

    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.

    0 讨论(0)
  • 2021-02-06 22:14

    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("^","");
    
    0 讨论(0)
  • 2021-02-06 22:23

    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("^", "");
    
    0 讨论(0)
提交回复
热议问题