C#: Find or replace first occurrence of character in string

If you program a lot with C#, for example in Visual Studio, it happens again and again that you want to process strings. A problem can be that you want to find a word, certain characters or whole sentences within a string, i.e. a substring, in order to replace it with something else, for example.

Replace() does not work

As is well known, there are always many or several ways to get to the target in programming languages. An obvious variant would be to simply use the Replace() function á la:

myText = myText.Replace("searchString", "replaceString");

Here “searchString” is the searched substring and “replaceString” is the string with which we want to replace “searchString”. In this case the string “myText” is searched.

The problem is that the Replace function replaces all occurrences of searchString. In our question, however, we only want to replace the first occurrence of a certain searched string. This means that you can only use Replace if you want to replace all occurrences.

Solution

First you have to find out the position where the string occurs first. This can be done with the IndexOf() function. Then you remove the string you are looking for from the string (Remove() function), and then insert the new string (Insert() function). In C# code the whole thing looks like this, where int i is the zero-based integer value at which position searchString was found the first time.

int i = myText.IndexOf("searchString");
myText = myText.Remove(i, "searchString".Length);
myText = myText.Insert(i, "replaceString");

 

Leave a Reply

Your email address will not be published. Required fields are marked *