Replace first occurrence of pattern in a string

C#Regex

C# Problem Overview


> Possible Duplicate:
> How do I replace the first instance of a string in .NET?

Let's say I have the string:

string s = "Hello world.";

how can I replace the first o in the word Hello for let's say Foo?

In other words I want to end up with:

"HellFoo world."

I know how to replace all the o's but I want to replace just the first one

C# Solutions


Solution 1 - C#

I think you can use the overload of Regex.Replace to specify the maximum number of times to replace...

var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);

Solution 2 - C#

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

here is an Extension Method that could also work as well per VoidKing request

public static class StringExtensionMethods
{
	public static string ReplaceFirst(this 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);
	}
}

Solution 3 - C#

There are a number of ways that you could do this, but the fastest might be to use IndexOf to find the index position of the letter you want to replace and then substring out the text before and after what you want to replace.

if (s.Contains("o"))
{
    s = s.Remove(s.IndexOf('o')) + "Foo" + s.Substring(s.IndexOf('o') + 1);
}

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
QuestionTono NamView Question on Stackoverflow
Solution 1 - C#ReddogView Answer on Stackoverflow
Solution 2 - C#MethodManView Answer on Stackoverflow
Solution 3 - C#Mitchel SellersView Answer on Stackoverflow