Tuesday, July 19, 2011

Case Insensitive Replace() function

For some reason .Net framework does not have the case insensitive replace method in the String class. I found it can very easily be implemented for String class using Extension Method feature of .Net.

Here's the method:
public static string Replace(this string originalString, string oldValue, string newValue, StringComparison comparisonType)
{
int startIndex = 0;
while (true)
{
startIndex = originalString.IndexOf(oldValue, startIndex, comparisonType);
if (startIndex == -1)
break;

originalString = originalString.Substring(0, startIndex) + newValue + originalString.Substring(startIndex + oldValue.Length);

startIndex += newValue.Length;
}

return originalString;
}


And calling this method seems trivial:
originalString = originalString.Replace(@"ABCD", "abcd", StringComparison.InvariantCultureIgnoreCase);


That's it.

No comments: