215

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

Community
  • 1
  • 1
Tono Nam
  • 34,064
  • 78
  • 298
  • 470
  • 2
    Voted to re-open this old question, which as _explicitly about **pattern** and **regular expression**_. While it an be simplified in this case to literals strings, it is not technically same as the actual ask. Unfortunately the duplicate is also tagged with 'regex', although it does not include 'pattern' anywhere. – user2864740 Sep 18 '20 at 21:53

3 Answers3

301

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);
Reddog
  • 15,219
  • 3
  • 51
  • 63
276
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);
    }
}
sgmoore
  • 15,694
  • 5
  • 43
  • 67
MethodMan
  • 18,625
  • 6
  • 34
  • 52
  • 17
    much better than the regex imho, this is what the regex will eventually do anyway, after skipping overhead. In very long strings with the result very far at the end, the regex impl might be better as it supports streaming the char array, but for small strings, this seems a lot more efficient... – Jaap Aug 06 '13 at 13:57
  • Never, ever do this. Use .Net. (ie, use the regex call made for this purpose.) – Fattie Apr 12 '22 at 10:44
  • 4
    @Fattie Care to explain why? – matronator May 28 '22 at 15:36
  • 1
    public static string ReplaceFirst(this string text, string search, string replace) { int pos = text.IndexOf(search); if (pos < 0) { return text; } string result = text.Remove(pos, search.Length).Insert(pos, replace); return result; } – sabiland Jun 09 '22 at 11:04
18

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);
}
Kech101
  • 5
  • 2
Mitchel Sellers
  • 62,228
  • 14
  • 110
  • 173