Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

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:

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

This just leaves the string as it was before. Can anyone please explain to me as to why?

like image 807
Ian Lundberg Avatar asked Apr 05 '12 00:04

Ian Lundberg


People also ask

How do you remove all occurrences of a substring from a string?

Example 1: Input: s = "daabcbaabcbc", part = "abc" Output: "dab" Explanation: The following operations are done: - s = "daabcbaabcbc", remove "abc" starting at index 2, so s = "dabaabcbc". - s = "dabaabcbc", remove "abc" starting at index 4, so s = "dababc".

Which string method would we use to remove all instances of a particular character from a string?

Using translate(): translate() is another method that can be used to remove a character from a string in Python. translate() returns a string after removing the values passed in the table. Also, remember that to remove a character from a string using translate() you have to replace it with None and not "" .

How do I remove the occurrence of a character from a string in Python?

Python Remove Character from String using replace() If we provide an empty string as the second argument, then the character will get removed from the string. Note that the string is immutable in Python, so this function will return a new string and the original string will remain unchanged.


1 Answers

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("^", ""); 
like image 118
Tim Schmelter Avatar answered Sep 17 '22 12:09

Tim Schmelter