Alternative to multiple String.Replaces [duplicate]

Solution 1:

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

Solution 2:

Are we going for ways to make this harder to understand what is going on?

If so regex is your friend

var replacements = new Dictionary<string,string>()
{
   {"somestring",someVariable1},
   {"anotherstring",someVariable2}
};

var regex = new Regex(String.Join("|",replacements.Keys.Select(k => Regex.Escape(k))));
var replaced = regex.Replace(input,m => replacements[m.Value]);

Live: http://rextester.com/SXXB8348

Solution 3:

You could at least chain the statements:

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

Solution 4:

Calling Replace three times is not only a valid answer, it might be the preferred one:

RegEx takes three steps: Parse, Execute, Formulate. But String.Replace is hard-coded, so in many cases it has superior speed. And a complex RegEx isn't as readable as a well-formatted chain of Replace statements. (Compare Jonathan's solution to Daniel's)

If you're still not convinced that Replace is better for your case, make a competition out of it! Try both methods side-by-side and use a Stopwatch to see how many milliseconds you save when using your data.

But DON'T optimize prematurely! Any developer will prefer readability and maintainability over a cryptic pile of spaghetti that performs three milliseconds faster.

Solution 5:

This article Regex: replace multiple strings in a single pass with C# can be helpful:

static string MultipleReplace(string text, Dictionary replacements) {
    return Regex.Replace(text, 
        "(" + String.Join("|", adict.Keys.ToArray()) + ")",
        delegate(Match m) { return replacements[m.Value]; }
    );
}

// somewhere else in code
string temp = "Jonathan Smith is a developer";
adict.Add("Jonathan", "David");
adict.Add("Smith", "Seruyange");
string rep = MultipleReplace(temp, adict);