C# StringBuilder
last modified November 15, 2026
This article shows how to build and modify strings efficiently with the
StringBuilder class in C#.
StringBuilder
A C# string is immutable. Methods like Replace or
Insert and the + operator never change a string;
they create a new one. When a string is built in many small steps, each step
copies all the text created so far.
StringBuilder from the System.Text namespace is a
mutable sequence of characters. It keeps its text in internal buffers with
spare room, so appending usually just copies the new characters. The final
string is created once, with ToString.
Use a StringBuilder when a string is built in a loop or from
many parts whose number is not known in advance. For a fixed number of parts,
string interpolation or string.Concat is simpler and just as
fast.
| Member | Description |
|---|---|
Append, AppendLine |
Add text to the end. |
AppendJoin, AppendFormat |
Add joined or formatted values. |
Insert |
Inserts text at a position. |
Replace |
Replaces characters or substrings. |
Remove, Clear |
Remove a range of characters or all of them. |
Length, Capacity, indexer |
Size, allocated room, and single characters. |
ToString |
Creates the resulting string. |
C# StringBuilder is mutable
The first example shows the main difference between string and
StringBuilder.
using System.Text;
var word = "rock";
var word2 = word.Replace('r', 'd');
Console.WriteLine($"{word} {word2}");
var builder = new StringBuilder("rock");
var same = builder.Replace('r', 'd');
Console.WriteLine(builder);
Console.WriteLine(ReferenceEquals(builder, same));
We replace a character in a string and in a builder.
var word2 = word.Replace('r', 'd');
String.Replace returns a modified copy; the original string is
unchanged.
var same = builder.Replace('r', 'd');
StringBuilder.Replace modifies the builder in place. It also
returns the builder itself, as the ReferenceEquals check shows.
This allows chaining calls.
Console.WriteLine(builder);
Console.WriteLine calls the ToString method of the
builder.
$ dotnet run rock dock dock True
C# StringBuilder Append and AppendLine
Append adds the text representation of a value to the end of the
builder. AppendLine adds an optional string followed by the line
terminator.
using System.Text;
var builder = new StringBuilder("There are");
builder.Append(' ');
builder.Append("three hawks ");
builder.Append("in the sky");
builder.AppendLine();
builder.AppendLine("The weather is beautiful");
builder.Append("Temperature: ").Append(23.5).Append(" \u00B0C, wind: ").Append(true);
builder.AppendLine();
builder.Append('-', 20);
Console.WriteLine(builder);
We build a short text from several parts.
builder.AppendLine();
Without arguments, AppendLine adds only the line terminator,
Environment.NewLine, which is "\n" on Linux and "\r\n" on
Windows.
builder.Append("Temperature: ").Append(23.5).Append(" \u00B0C, wind: ").Append(true);
Append has overloads for all basic types, so numbers and booleans
are added without creating temporary strings. Since each call returns the
builder, the calls can be chained.
builder.Append('-', 20);
This overload appends a character repeated the given number of times.
$ dotnet run There are three hawks in the sky The weather is beautiful Temperature: 23.5 °C, wind: True --------------------
C# StringBuilder AppendJoin
AppendJoin appends the elements of a collection with a separator
between them. It is the StringBuilder version of
string.Join.
using System.Text;
string[] words = ["in", "the", "sky"];
var builder = new StringBuilder("There are three hawks ");
builder.AppendJoin(" ", words);
builder.Append('.');
Console.WriteLine(builder);
List<int> nums = [1, 2, 3, 4];
builder.Clear().AppendJoin(", ", nums);
Console.WriteLine(builder);
We append the elements of an array and a list.
builder.AppendJoin(" ", words);
The words of the array are appended, separated by spaces.
builder.Clear().AppendJoin(", ", nums);
For elements that are not strings, ToString is called on each of
them. Here we clear the builder and append a list of integers.
$ dotnet run There are three hawks in the sky. 1, 2, 3, 4
C# StringBuilder formatting
Formatted text can be appended with AppendFormat, which takes a
composite format string, or with an interpolated string.
using System.Globalization;
using System.Text;
string name = "Peter";
int age = 34;
decimal salary = 2150.5m;
var builder = new StringBuilder();
builder.AppendFormat("{0} is {1} years old", name, age).AppendLine();
builder.AppendFormat(CultureInfo.InvariantCulture, "{0,-8}|{1,8:F2}|", name, salary)
.AppendLine();
builder.Append($"{name} earns {salary:F2} a month");
builder.AppendLine();
var de = new CultureInfo("de-DE");
builder.Append(de, $"{name} earns {salary:N2} EUR");
Console.WriteLine(builder);
We append formatted values in several ways.
builder.AppendFormat("{0} is {1} years old", name, age).AppendLine();
AppendFormat works like string.Format; the
placeholders refer to the arguments by their index.
builder.AppendFormat(CultureInfo.InvariantCulture, "{0,-8}|{1,8:F2}|", name, salary)
The first argument can be a format provider. The placeholders can contain an alignment and a format string; here the name is left-aligned in eight characters and the salary right-aligned with two decimal places.
builder.Append($"{name} earns {salary:F2} a month");
When an interpolated string is passed to Append, the compiler
uses a special interpolated string handler (.NET 6). The values are formatted
directly into the builder, and no temporary string is created.
builder.Append(de, $"{name} earns {salary:N2} EUR");
An overload takes the culture used for formatting. The German culture uses a dot as the thousands separator and a comma for decimals.
$ dotnet run Peter is 34 years old Peter | 2150.50| Peter earns 2150.50 a month Peter earns 2.150,50 EUR
C# StringBuilder Insert
Insert puts text at the given index. The characters after it are
shifted, so inserting near the start of a long text is slower than
appending.
using System.Text;
var builder = new StringBuilder("There is a red fox in the forest.");
builder.Insert(19, "and a wolf ");
Console.WriteLine(builder);
builder.Insert(0, "Look! ");
Console.WriteLine(builder);
int idx = builder.ToString().IndexOf("forest");
builder.Insert(idx, "dark ");
Console.WriteLine(builder);
We insert words into a sentence.
builder.Insert(19, "and a wolf ");
The text is inserted at index 19, right after "fox ".
int idx = builder.ToString().IndexOf("forest");
builder.Insert(idx, "dark ");
StringBuilder has no IndexOf method. To find a
position, we search the string created by ToString.
$ dotnet run There is a red fox and a wolf in the forest. Look! There is a red fox and a wolf in the forest. Look! There is a red fox and a wolf in the dark forest.
C# StringBuilder Replace
Replace replaces all occurrences of a character or a substring.
An overload limits the replacement to a range of the builder.
using System.Text;
var builder = new StringBuilder("I saw a red fox and a brown fox in the forest.");
builder.Replace("fox", "dog", 0, 15);
Console.WriteLine(builder);
builder.Replace("fox", "wolf");
Console.WriteLine(builder);
builder.Replace(' ', '_');
Console.WriteLine(builder);
We replace words and characters.
builder.Replace("fox", "dog", 0, 15);
The last two arguments are the start index and the length of the range in which the replacement happens. Only the first "fox" lies within the first 15 characters, so the second one stays.
builder.Replace("fox", "wolf");
Without the range, all occurrences are replaced.
$ dotnet run I saw a red dog and a brown fox in the forest. I saw a red dog and a brown wolf in the forest. I_saw_a_red_dog_and_a_brown_wolf_in_the_forest.
C# StringBuilder Remove and Length
Remove deletes a range of characters. The Length
property can be set as well; setting it to a smaller value truncates the
text.
using System.Text;
var builder = new StringBuilder("There is a red fox in the forest.");
builder.Remove(11, 4);
Console.WriteLine(builder);
builder.Length--;
Console.WriteLine(builder);
builder.Length = 14;
Console.WriteLine(builder);
We shorten a sentence in three ways.
builder.Remove(11, 4);
We remove four characters starting at index 11, which is the word "red" and the space after it.
builder.Length--;
Decreasing the length by one removes the last character, here the dot. This is a quick way to drop a trailing separator after a loop.
builder.Length = 14;
The builder keeps only its first fourteen characters. Setting a greater length would pad the text with null characters.
$ dotnet run There is a fox in the forest. There is a fox in the forest There is a fox
C# StringBuilder indexer
Single characters are read and written with the indexer.
using System.Text;
var builder = new StringBuilder("falcon");
Console.WriteLine(builder[0]);
Console.WriteLine(builder[^1]);
builder[0] = char.ToUpper(builder[0]);
Console.WriteLine(builder);
for (int i = 0; i < builder.Length / 2; i++)
{
(builder[i], builder[builder.Length - 1 - i]) = (builder[builder.Length - 1 - i], builder[i]);
}
Console.WriteLine(builder);
Console.WriteLine(builder.ToString(1, 3));
We capitalize a word and reverse it in place.
builder[0] = char.ToUpper(builder[0]);
Unlike a string, a builder allows changing a character at a given index.
for (int i = 0; i < builder.Length / 2; i++)
{
(builder[i], builder[builder.Length - 1 - i]) = (builder[builder.Length - 1 - i], builder[i]);
}
We swap the characters from both ends with a tuple assignment. The indexer of a large builder that has grown in many steps can be slow, because the text is stored in a linked list of chunks that must be searched.
Console.WriteLine(builder.ToString(1, 3));
This ToString overload returns a substring: three characters
starting at index 1.
$ dotnet run f n Falcon noclaF ocl
C# StringBuilder capacity
Length is the number of characters in the builder;
Capacity is the number of characters that fit into the memory
allocated so far.
using System.Text;
var builder = new StringBuilder();
Console.WriteLine($"Length: {builder.Length}, Capacity: {builder.Capacity}");
builder.Append("an old falcon");
Console.WriteLine($"Length: {builder.Length}, Capacity: {builder.Capacity}");
builder.Append(" in the sky");
Console.WriteLine($"Length: {builder.Length}, Capacity: {builder.Capacity}");
var builder2 = new StringBuilder(1000);
Console.WriteLine($"Length: {builder2.Length}, Capacity: {builder2.Capacity}");
builder.Clear();
Console.WriteLine($"Length: {builder.Length}, Capacity: {builder.Capacity}");
Console.WriteLine(builder.MaxCapacity);
We watch the capacity while the builder grows.
var builder = new StringBuilder();
A new builder has room for sixteen characters. When it is full, the builder allocates a new chunk and links it to the previous one; the existing text is not copied.
var builder2 = new StringBuilder(1000);
If we know the approximate size of the result, we pass it to the constructor and the builder allocates enough room at once.
builder.Clear();
Clear sets the length to zero but keeps an allocated buffer for
reuse; the capacity is not reset to 16.
$ dotnet run Length: 0, Capacity: 16 Length: 13, Capacity: 16 Length: 24, Capacity: 32 Length: 0, Capacity: 1000 Length: 0, Capacity: 28 2147483647
C# StringBuilder reuse and equality
A builder can be cleared and reused. Two builders are compared with
Equals.
using System.Text;
var builder = new StringBuilder();
foreach (var word in new[] { "sky", "cloud", "rain" })
{
builder.Clear();
builder.Append('<').Append(word).Append('>');
Console.WriteLine(builder);
}
var b1 = new StringBuilder("sky");
var b2 = new StringBuilder("sky");
Console.WriteLine(b1 == b2);
Console.WriteLine(b1.Equals(b2));
Console.WriteLine(b1.Equals("sky".AsSpan()));
We reuse one builder in a loop and compare builders.
builder.Clear();
builder.Append('<').Append(word).Append('>');
Clear returns the builder, so further calls can be chained to
it. Reusing a builder saves allocations in a tight loop.
Console.WriteLine(b1 == b2); Console.WriteLine(b1.Equals(b2));
StringBuilder does not overload the == operator, so
it compares references. Equals(StringBuilder) compares the
contents.
Console.WriteLine(b1.Equals("sky".AsSpan()));
An overload compares the builder with a span of characters without creating a string.
$ dotnet run <sky> <cloud> <rain> False True True
C# StringBuilder performance
The last example compares building a long string with the +=
operator and with a StringBuilder.
using System.Diagnostics;
using System.Text;
const int n = 100_000;
var sw = Stopwatch.StartNew();
string s = "";
for (int i = 0; i < n; i++)
{
s += i % 10;
}
Console.WriteLine($"string {sw.ElapsedMilliseconds,5} ms");
sw.Restart();
var builder = new StringBuilder();
for (int i = 0; i < n; i++)
{
builder.Append(i % 10);
}
string s2 = builder.ToString();
Console.WriteLine($"StringBuilder {sw.ElapsedMilliseconds,5} ms");
Console.WriteLine(s == s2);
We create a string of 100,000 digits.
s += i % 10;
Each += creates a new string and copies the old one into it. In
total, about five billion characters are copied.
builder.Append(i % 10);
The builder copies each digit once. The exact times depend on the machine, but the difference is several orders of magnitude.
$ dotnet run string 621 ms StringBuilder 0 ms True
Source
StringBuilder class - .NET API
Using the StringBuilder class in .NET
In this article we have worked with the C# StringBuilder
class. See also the string,
add string,
string interpolation, and
List to string tutorials.
Author
List all C# tutorials.