C# StringBuilder Replace Example

In this source code example, we will demonstrate the usage of the StringBuilder Replace method in C# with an example.

The Replace method replaces a substring in the string builder with the specified new string.

C# StringBuilder Replace Example

The below example replaces the word fox with dog:
using System;
using System.Text;

class StringBuilderExample {
    static void Main() {
        var sentence = "I saw a red fox running into the forest.";
        var builder = new StringBuilder(sentence);
        
        var term = "fox";
        var newterm = "dog";
        
        int idx = builder.ToString().IndexOf(term);
        int len = term.Length;
        
        builder.Replace(term, newterm, idx, idx + len);
        
        Console.WriteLine(builder);
    }
}

Output:

I saw a red dog running into the forest.

Comments