Search code examples
c#stringextension-methodsstring-operations

C# String append some string ater first occurance of a string after a given string


I know this seems to be very complicated but what i mean is for example i have a string

This is a text string 

I want to search for a string (for example: text) . I want to find first occurance of this string which comes after a given another string (for example : is) and the replacement should be another string given (for example: replace)

So the result should be:

This is a textreplace string

If text is This text is a text string then the result should be This text is a textreplace string

I need a method (extension method is appreciated):

public static string AppendFirstOccurranceAfter(this string originalText, string after, string oldValue, string newValue)
// "This is a text string".ReplaceFirstOccurranceAfter("is", "text", "replace")

Solution

  • You have to find the index of the first word to match and then, using that index, do another search for the second word starting at that said index and then you can insert your new text. You can find said indexes with the IndexOf method (check it's overloads).

    Here is a simple solution written in a way that (I hope) is readable and that you can likely improve to make more idiomatic:

        public static string AppendFirstOccurranceAfter(this string originalText, string after, string oldValue, string newValue) {
        var idxFirstWord = originalText.IndexOf(after);
        var idxSecondWord = originalText.IndexOf(oldValue, idxFirstWord);
        var sb = new StringBuilder();
    
        for (int i = 0; i < originalText.Length; i++) {
            if (i == (idxSecondWord + oldValue.Length))
                sb.Append(newValue);
            sb.Append(originalText[i]);
        }
    
        return sb.ToString();
    }