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?
Asked
Active
Viewed 497 times
-2
-
regular expressions. – Daniel A. White May 29 '19 at 17:21
-
1Look up IndexOf ! – TaW May 29 '19 at 17:22
-
1can you provide code with input string and expected output – Prasad Telkikar May 29 '19 at 17:22
-
Note: The question is unclear: Do you mean first instance of a string or of a word?? – TaW May 29 '19 at 17:24
1 Answers
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