Instead of using Replace
again and again, you can simply write your own. It may even improve performance, as you mentioned
But my array can get a lot more.
public string Replace(string original, char replacement, params char[] replaceables) { StringBuilder builder = new StringBuilder(original.Length); HashSet<char> replaceable = new HashSet<char>(replaceables); foreach(Char character in original) { if (replaceable.Contains(character)) builder.Append(replacement); else builder.Append(character); } return builder.ToString(); } public string Replace(string original, char replacement, string replaceables) { return Replace(original, replacement, replaceables.ToCharArray()); }
You can call it like this:
Debug.WriteLine(Replace("a/ new string, with some@ values&", '_', '/', '@', '&')); Debug.WriteLine(Replace("a/ new string, with some@ values&", '_', new[] { '/', '@', '&' })); Debug.WriteLine(Replace("a/ new string, with some@ values&", '_', existingArray)); Debug.WriteLine(Replace("a/ new string, with some@ values&", '_',"/@&"));
Output:
a_ new string, with some_ values_ a_ new string, with some_ values_ a_ new string, with some_ values_ a_ new string, with some_ values_
As @Sebi noted, this will also work as an extension method:
public static class StringExtensions { public static string Replace(this string original, char replacement, params char[] replaceables) { StringBuilder builder = new StringBuilder(original.Length); HashSet<Char> replaceable = new HashSet<char>(replaceables); foreach (Char character in original) { if (replaceable.Contains(character)) builder.Append(replacement); else builder.Append(character); } return builder.ToString(); } public static string Replace(this string original, char replacement, string replaceables) { return Replace(original, replacement, replaceables.ToCharArray()); } }
Using:
"a/ new string, with some@ values&".Replace('_', '/', '@', '&'); existingString.Replace('_', new[] { '/', '@', '&' });