Case Insensitive String Extension Method
Posted on: Wed Feb 10 18:08:16 -0800 2010. Updated on: Wed Feb 10 18:10:24 -0800 2010.
Category: .NET C#
Category: .NET C#
The default String.Replace is not case Insensitive, here is a quick extension method you could add to get a String.ReplaceCI that would do this. I like extension methods.
public static class StringExtensions
{
public static string ReplaceCI(this String sourceString, string searchString, string replaceString)
{
if (searchString == null) throw new ArgumentNullException("searchString");
if (replaceString == null) throw new ArgumentNullException("replaceString");
StringBuilder retVal = new StringBuilder(sourceString.Length);
int ptr = 0, lastPtr = 0;
while (ptr >= 0)
{
ptr = sourceString.IndexOf(searchString, ptr, StringComparison.OrdinalIgnoreCase);
int strLength = ptr - lastPtr;
if (strLength > 0 || ptr == 0)
{
if (ptr > 0)
retVal.Append(sourceString.Substring(lastPtr, strLength));
retVal.Append(replaceString);
ptr += searchString.Length;
}
else
break;
lastPtr = ptr;
}
if (lastPtr >= 0)
retVal.Append(sourceString.Substring(lastPtr));
return retVal.ToString();
}
}
Ideas were borrowed from this guy: Case Insensitive String