Alternative to multiple String.Replaces
C#StringReplaceC# Problem Overview
My code uses String.Replace
several times in a row:
mystring = mystring.Replace("somestring", variable1);
mystring = mystring.Replace("somestring2", variable2);
mystring = mystring.Replace("somestring3", variable1);
I suspect there's a better and faster way to do it. What would you suggest?
C# Solutions
Solution 1 - C#
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 - C#
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]);
Solution 3 - C#
You could at least chain the statements:
mystring = mystring.Replace("somestring", variable1)
.Replace("somestring2", variable2)
.Replace("somestring3", variable3);
Solution 4 - C#
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 - C#
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);
Solution 6 - C#
Depending how your data is organized (what you're replacing) or how many you have; an array and loops might be a good approach.
string[] replaceThese = {"1", "2", "3"};
string data = "replace1allthe2numbers3";
foreach (string curr in replaceThese)
{
data = data.Replace(curr, string.Empty);
}
Solution 7 - C#
If you don't want to use RegEx add this class to your project,
It uses an extension method 'MultipleReplace':
public static class StringExtender
{
public static string MultipleReplace(this string text, Dictionary<string, string> replacements)
{
string retVal = text;
foreach (string textToReplace in replacements.Keys)
{
retVal = retVal.Replace(textToReplace, replacements[textToReplace]);
}
return retVal;
}
}
Then you can use this piece of code:
string mystring = "foobar";
Dictionary<string, string> stringsToReplace = new Dictionary<string,string>();
stringsToReplace.Add("somestring", variable1);
stringsToReplace.Add("somestring2", variable2);
stringsToReplace.Add("somestring3", variable1);
mystring = mystring.MultipleReplace(stringsToReplace);
Solution 8 - C#
My preferred method is to use the power of Regex
to solve a multiple replace problem. The only issue with this approach is you only get to choose one string
to replace with.
The following will replace all '/'
or ':'
with a '-'
to make a valid file name.
Regex.Replace("invalid:file/name.txt", @"[/:]", "-");