Takes a string and replaces all characters matching a given array with a given string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public static class StringExtensions
{
public static string Replace(this String str, char[] chars, string replacement)
{
StringBuilder output = new StringBuilder(str.Length);
for (int i = 0; i < str.Length; i++)
{
char c = str[i];
bool replace = false;
for (int j = 0; j < chars.Length; j++)
{
if (chars[j] == c)
{
replace = true;
break;
}
}
if (replace)
output.Append(replacement);
else
output.Append(c);
}
return output.ToString();
}
}
|
It's a mash-up of String.Trim(params char[] trimChars) and String.Replace(string oldValue, string newValue).