A few weeks ago a colleague asked me if there was a case insensitive string replacement function in .NET.
As far as I know there isn’t, but there is a case insensitive overload for the String.IndexOf which allows you to easily write your own. Here’s a sample one;
/// <summary>
/// Performs either a case sensitive or case insensitive search and replace on the specified string.
/// </summary>
/// <param name="sourceString">The string containing the data to be replaced.</param>
/// <param name="searchString">The substring to find (and replace).</param>
/// <param name="replaceString">The string to replace searchString with.</param>
/// <param name="caseSensitive">A boolean indicating whether or not this replace is case sensitive.</param>
/// <returns>A new string where all instances of the substring specified by searchString have been replaced with the one provided by replaceString.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "string")]
public static string Replace(string sourceString, string searchString, string replaceString, bool caseSensitive)
{
if (sourceString == null) throw new ArgumentNullException("sourceString");
if (searchString == null) throw new ArgumentNullException("searchString");
if (String.IsNullOrEmpty(searchString)) throw new ArgumentException("searchString cannot be an empty string.", "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, caseSensitive ? StringComparison.InvariantCulture : 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) //Append the piece of the string left after the last occurrence of searchString, if any.
retVal.Append(sourceString.Substring(lastPtr));
return retVal.ToString();
}
6 comments: