Petter Brodin Petter Brodin - 3 months ago 13
C# Question

Alternative to String.Replace multiple times?

I've got some code that uses String.Replace several times in a row, and I suspect there's a better and faster way to do it:

mystring = mystring.Replace("somestring", variable1);
mystring = mystring.Replace("somestring2", variable2);
mystring = mystring.Replace("somestring3", variable1);


What would you suggest to use instead?

Answer

For an 'easy' alternative just use a StringBuilder....

StringBuilder sb = new StringBuilder("11223344");

string myString =
    sb
      .Replace("1", string.Empty)
      .Replace("2", string.Empty)
      .Replace("3", string.Empty)
      .ToString();