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

C#.NetRegexStringReplace

C# Problem Overview


I want to replace the first occurrence in a given string.

How can I accomplish this in .NET?

C# Solutions


Solution 1 - C#

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");

Solution 2 - C#

As itsmatt said Regex.Replace is a good choice for this however to make his answer more complete I will fill it in with a code sample:

using System.Text.RegularExpressions;
...
Regex regex = new Regex("foo");
string result = regex.Replace("foo1 foo2 foo3 foo4", "bar", 1);             
// result = "bar1 foo2 foo3 foo4"

The third parameter, set to 1 in this case, is the number of occurrences of the regex pattern that you want to replace in the input string from the beginning of the string.

I was hoping this could be done with a static Regex.Replace overload but unfortunately it appears you need a Regex instance to accomplish it.

Solution 3 - C#

Take a look at Regex.Replace.

Solution 4 - C#

using System.Text.RegularExpressions;

RegEx MyRegEx = new RegEx("F");
string result = MyRegex.Replace(InputString, "R", 1);

will find first F in InputString and replace it with R.

Solution 5 - C#

Taking the "first only" into account, perhaps:

int index = input.IndexOf("AA");
if (index >= 0) output = input.Substring(0, index) + "XQ" +
     input.Substring(index + 2);

?

Or more generally:

public static string ReplaceFirstInstance(this string source,
    string find, string replace)
{
    int index = source.IndexOf(find);
    return index < 0 ? source : source.Substring(0, index) + replace +
         source.Substring(index + find.Length);
}

Then:

string output = input.ReplaceFirstInstance("AA", "XQ");

Solution 6 - C#

In C# syntax:

int loc = original.IndexOf(oldValue);
if( loc < 0 ) {
    return original;
}
return original.Remove(loc, oldValue.Length).Insert(loc, newValue);

Solution 7 - C#

C# extension method that will do this:

public static class StringExt
{
    public static string ReplaceFirstOccurrence(this string s, string oldValue, string newValue)
    {
         int i = s.IndexOf(oldValue);
         return s.Remove(i, oldValue.Length).Insert(i, newValue);    
    } 
}

Solution 8 - C#

Assumes that AA only needs to be replaced if it is at the very start of the string:

var newString;
if(myString.StartsWith("AA"))
{
  newString ="XQ" + myString.Substring(2);
}

If you need to replace the first occurrence of AA, whether the string starts with it or not, go with the solution from Marc.

Solution 9 - C#

And because there is also VB.NET to consider, I would like to offer up:

Private Function ReplaceFirst(ByVal text As String, ByVal search As String, ByVal replace As String) As String
    Dim pos As Integer = text.IndexOf(search)
    If pos >= 0 Then
        Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)
    End If
    Return text 
End Function

Solution 10 - C#

One of the overloads of Regex.Replace takes an int for "The maximum number of times the replacement can occur". Obviously, using Regex.Replace for plain text replacement may seem like overkill, but it's certainly concise:

string output = (new Regex("AA")).Replace(input, "XQ", 1);

Solution 11 - C#

For anyone that doesn't mind a reference to Microsoft.VisualBasic, there is the Replace Method:

string result = Microsoft.VisualBasic.Strings.Replace("111", "1", "0", 2, 1); // "101"

Solution 12 - C#

This example abstracts away the substrings (but is slower), but is probably much fast than a RegEx:

var parts = contents.ToString().Split(new string[] { "needle" }, 2, StringSplitOptions.None);
return parts[0] + "replacement" + parts[1];

Solution 13 - C#

Updated extension method utilizing Span to minimize new string creation

	public static string ReplaceFirstOccurrence(this string source, string search, string replace) {
		int index = source.IndexOf(search);
		if (index < 0) return source;
		var sourceSpan = source.AsSpan();
		return string.Concat(sourceSpan.Slice(0, index), replace, sourceSpan.Slice(index + search.Length));
	}

Solution 14 - C#

With ranges and C# 10 we can do:

public static string ReplaceFirst(this string text, string search, string replace)
{
    int pos = text.IndexOf(search, StringComparison.Ordinal);
    return pos < 0 ? text : string.Concat(text[..pos], replace, text.AsSpan(pos + search.Length));
}

Solution 15 - C#

string abc = "AAAAX1";

            if(abc.IndexOf("AA") == 0)
            {
                abc.Remove(0, 2);
                abc = "XQ" + abc;
            }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNirmalView Question on Stackoverflow
Solution 1 - C#VVSView Answer on Stackoverflow
Solution 2 - C#Wes HaggardView Answer on Stackoverflow
Solution 3 - C#itsmattView Answer on Stackoverflow
Solution 4 - C#DeeneshView Answer on Stackoverflow
Solution 5 - C#Marc GravellView Answer on Stackoverflow
Solution 6 - C#Bill the LizardView Answer on Stackoverflow
Solution 7 - C#mortenbpostView Answer on Stackoverflow
Solution 8 - C#OdedView Answer on Stackoverflow
Solution 9 - C#Anthony PottsView Answer on Stackoverflow
Solution 10 - C#AakashMView Answer on Stackoverflow
Solution 11 - C#SlaiView Answer on Stackoverflow
Solution 12 - C#user3638471View Answer on Stackoverflow
Solution 13 - C#Brad PattonView Answer on Stackoverflow
Solution 14 - C#Matěj ŠtáglView Answer on Stackoverflow
Solution 15 - C#Mazhar KarimiView Answer on Stackoverflow