-2

I need to replace the first instance of a word in a string with another string. The problem is that the word being replaced sometimes appears more than once in the string that is being changed. When that happens we only want the first instance to be replaced. How can I do that?

Chad
  • 1,512
  • 1
  • 16
  • 40

1 Answers1

3
        string s1 = "something replace replace replace replace something";
        string s2 = "replace";
        string newString=s1;

        int index = s1.IndexOf(s2);
        if (index > -1)
        {
            newString = s1.Substring(0, index) + "newWord" + s1.Substring(index + s2.Length);
        }  
        Console.WriteLine(newString);
Mike
  • 5,918
  • 9
  • 57
  • 94