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;
}

Hire Me

Follow me on Facebook

Follow me

Do you find this Blog helpful?

Follow by Email

About Me

My Photo
Expert Senior Software Developer

Microsoft Business Card