C# StringBuilder Replace() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
StringBuilder

Definition

In C#, StringBuilder.Replace(oldValue, newValue) finds every occurrence of oldValue in the builder and puts newValue in its place. It works with strings and with single characters, and two more overloads limit the search to a range of positions.

The search is ordinal: it compares the exact characters, so it is case-sensitive and ignores culture rules. string.Replace returns a new string each time; the builder version edits in place and returns itself, which makes chains like .Replace("{a}", x).Replace("{b}", y) cheap.

An instance method of StringBuilder (using System.Text;), called as sb.Replace(...). The builder is a mutable buffer that changes in place, unlike an immutable string. It is not thread-safe.

Syntax

Pass what to find and what to put instead. Add a start position and a count to work on part of the text.

C#
StringBuilder sb = new StringBuilder("a-b-c");
sb.Replace("-", " + ");        // a + b + c
sb.Replace('a', 'x');          // x + b + c
sb.Replace("+", "&", 0, 4);    // x & b + c  (only the first 4 chars)
CallWhat it does
sb.Replace("old", "new")Replaces every old in the whole text.
sb.Replace('.', ',')Replaces every . character with ,.
sb.Replace("x", "y", 4, 6)Only looks inside the 6 characters starting at index 4.
sb.Replace("word", "")An empty (or null) new value deletes the matches.

oldValue cannot be null (ArgumentNullException) or empty (ArgumentException). For the range overloads, startIndex + count must fit inside Length, or ArgumentOutOfRangeException is thrown. There is no ignore-case option; for that, work on ToString() with StringComparison.OrdinalIgnoreCase.

Library declarations
C#
public StringBuilder Replace(string oldValue, string? newValue);
public StringBuilder Replace(string oldValue, string? newValue, int startIndex, int count);
public StringBuilder Replace(char oldChar, char newChar);
public StringBuilder Replace(char oldChar, char newChar, int startIndex, int count);

Parameters

ParameterDescription
oldValue / oldCharRequired. The text or character to find. A string must not be empty.
newValue / newCharRequired. What to put instead. An empty or null string removes the matches.
startIndex, countOptional. Limit the search to count characters starting at startIndex.

Return Value

Return ValueDescription
StringBuilderThe same builder, with all matches replaced. If nothing matched, the text is unchanged.

C# Examples

Example 1 — Replace Every Word and Every Character

Swap a word that appears twice, then swap a punctuation character everywhere.

C#
using System;
using System.Text;

class Program {
    static void Main() {
        StringBuilder sb = new StringBuilder("I like cats. cats are cute.");

        sb.Replace("cats", "dogs");
        Console.WriteLine(sb.ToString());

        sb.Replace('.', '!');
        Console.WriteLine(sb.ToString());
    }
}

How It Works

  1. All matches, not just the first. Replace("cats", "dogs") changes both cats in one call.
  2. Same length here. cats and dogs both have 4 letters, but different lengths are fine too; the builder grows or shrinks as needed.
  3. Character overload. Replace('.', '!') swaps single characters, so both full stops become exclamation marks.
  4. Edited in place. Each call changes sb itself, so the second print shows both replacements together.

Example 2 — Replace Inside a Range Only

Use the overloads with startIndex and count so that only the first part of the text changes.

C#
using System;
using System.Text;

class Program {
    static void Main() {
        StringBuilder sb = new StringBuilder("a-b-c-d-e");
        sb.Replace('-', '+', 0, 4);
        Console.WriteLine(sb.ToString());

        StringBuilder pets = new StringBuilder("cat cat cat");
        pets.Replace("cat", "dog", 4, 7);
        Console.WriteLine(pets.ToString());
    }
}

How It Works

  1. A window of 4. Replace('-', '+', 0, 4) only looks at a-b-, so the two dashes inside it change and the later ones stay.
  2. Skip the first word. In cat cat cat, index 4 is the start of the second cat, and 7 characters reach the end of the text.
  3. Matches must fit. Only words that lie completely inside the window are replaced, so the first cat is left alone.
  4. Range rules. 4 + 7 = 11, which equals Length, so the range is valid. One more character would throw ArgumentOutOfRangeException.

Example 3 — Fill a Message Template and Delete Filler Words

Chain two replacements to fill placeholders, then delete a word by replacing it with an empty string and see that the match is case-sensitive.

C#
using System;
using System.Text;

class Program {
    static void Main() {
        StringBuilder mail = new StringBuilder("Hi {name}, your code is {code}. Bye {name}!");
        mail.Replace("{name}", "Ravi").Replace("{code}", "A7");
        Console.WriteLine(mail.ToString());

        StringBuilder talk = new StringBuilder("um, so, UM, yes");
        talk.Replace("um, ", "");
        Console.WriteLine(talk.ToString());
    }
}

How It Works

  1. Placeholders are plain text. {name} has no special meaning to Replace; it is just a string to find, and it appears twice.
  2. Chain the fills. The first call returns the builder, so .Replace("{code}", "A7") continues on the same text without a temporary string.
  3. Delete by replacing. Replacing "um, " with "" removes it, together with its comma and space.
  4. Case matters. The search is ordinal, so the capital UM, does not match and stays in the result.

Frequently Asked Questions

It replaces every occurrence of a string or character inside the builder with another one, and returns the same builder.
No. It replaces all matches. To limit it, use the overload with startIndex and count, which only searches part of the text.
Yes. It uses ordinal comparison, so "Cat" and "cat" are different. There is no ignore-case overload.
Pass an empty string (or null) as the new value, for example sb.Replace(" ", "") removes every space.
string.Replace returns a new string and leaves the original as it was. StringBuilder.Replace edits the builder itself, which is cheaper when you make many replacements.

Next: ToString()

Turn the builder (or part of it) into a normal string you can print, store, or compare.

ToString() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful