ReplaceIgnoreCase
ReplaceIgnoreCase
Source
/// <summary>
/// Extension method to do case-insensitive string replace
/// </summary>
/// <param name="str"> </param>
/// <param name="pattern"> </param>
/// <param name="replacement"></param>
/// <returns></returns>
public static string ReplaceIgnoreCase(this string str, string pattern, string replacement)
{
int count, position0, position1;
count = position0 = position1 = 0;
string upperString = str.ToUpper();
string upperPattern = pattern.ToUpper();
int inc = (str.Length / pattern.Length) *
(replacement.Length - pattern.Length);
char[] chars = new char[str.Length + Math.Max(0, inc)];
while ((position1 = upperString.IndexOf(upperPattern,
position0)) != -1)
{
for (int i = position0; i < position1; ++i)
chars[count++] = str[i];
for (int i = 0; i < replacement.Length; ++i)
chars[count++] = replacement[i];
position0 = position1 + pattern.Length;
}
if (position0 == 0) return str;
for (int i = position0; i < str.Length; ++i)
chars[count++] = str[i];
return new string(chars, 0, count);
}
Example
var @string = ReplaceIgnoreCase("Test replace, test replace.", "Test", "tested");