Friday, June 1, 2012

How to Replace the First Instance of a String in C#

Assume that you have a string and you expect that this string might have some duplicated instances.

String.Replace() is very good Function, but it will replace all the instances of the string. So to accomplish this you need to replace the first instance you find.

The next code example can be used as a helper method in your project if you are dealing with strings frequently:

public static string ReplaceFirst(string str, string term, string replace)
{
    int position = str.IndexOf(term);

    if (position < 0)
    {
        return str;
    }

    str = str.Substring(0, position) + replace + str.Substring(position + term.Length);

    return str;
}

Source: https://www.nilebits.com/blog/2011/05/how-to-replace-the-first-instance-of-a-string-in-c-net/