Can
Can

Reputation: 709

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")

Upvotes: 0

Views: 661

Answers (2)

Cristiano Morgado
Cristiano Morgado

Reputation: 68

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();
}

Upvotes: 1

benjamin
benjamin

Reputation: 1654

Here is the extension method:

        public static string CustomReplacement(this string str)
        {
            string find = "text"; // What you are searching for
            char afterFirstOccuranceOf = 'a'; // The character after the first occurence of which you need to find your search term.
            string replacement = "$1$2replace"; // What you will replace it with. $1 is everything before the first occurrence of 'a' and $2 is the term you searched for.

            string pattern = $"([^{afterFirstOccuranceOf}]*{afterFirstOccuranceOf}.*)({find})";

            return Regex.Replace(str, pattern, replacement);
        }

You can use it like this:


string test1 = "This is a text string".CustomReplacement();
string test2 = "This text is a text string".CustomReplacement();

This solution uses C# Regular Expressions. The documentation from Microsoft is here: https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference

Upvotes: 1

Related Questions