How do I replace the *first instance* of a string in .NET?

string ReplaceFirst(string text, string search, string replace)
{
  int pos = text.IndexOf(search);
  if (pos < 0)
  {
    return text;
  }
  return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}

Example:

string str = "The brown brown fox jumps over the lazy dog";

str = ReplaceFirst(str, "brown", "quick");

EDIT: As @itsmatt mentioned, there’s also Regex.Replace(String, String, Int32), which can do the same, but is probably more expensive at runtime, since it’s utilizing a full featured parser where my method does one find and three string concatenations.

EDIT2: If this is a common task, you might want to make the method an extension method:

public static class StringExtension
{
  public static string ReplaceFirst(this string text, string search, string replace)
  {
     // ...same as above...
  }
}

Using the above example it’s now possible to write:

str = str.ReplaceFirst("brown", "quick");

Leave a Comment