String Replace extension method with string comparison ignore case support

by John Nye

20 Jan
2014

While writing some code for my NinjaNye.SearchExtensions project, I needed find and replace a string with another string, crucially with StringComparison support so that users could specifically choose the culture and case rules for searching.

Here is how I did it (as to my surprise, this is not supported by default as part of the string Replace() method)

internal static class StringExtensions
{
    public static string Replace(this string text, string oldValue, string newValue, 
                                 StringComparison stringComparison)
    {
        int position;
        while ((position = text.IndexOf(oldValue, stringComparison)) > -1)
        {
            text = text.Remove(position, oldValue.Length);
            text = text.Insert(position, newValue);
        }
        return text;
    }
}

As you can see this is a simple extension method that utilizes the IndexOf method to use the supplied StringComparison enumeration.

Usage of this method is as simple as the existing string Replace methods:

string text = "John Nye made this Extension method";
string newText = text.Replace("extension", "handy", StringComparison.OrdinalIgnoreCase);

The newText variable now equals "John Nye made this handy method", despite the case difference in the word "Extension".

Hope this is helpful to some of you out there.

For those interested in my SearchExtensions project, you can read more about it on the projects github pages. Alternatively checkout the SearchExtensions nuget package or install it by running the following in you package manager console

PM> Install-Package NinjaNye.SearchExtensions

Comments 0 * Be the first to comment!

Leave a message...

30 Mar
2017