C# StringBuilder
A StringBuilder is a text buffer that builds a string piece by piece. Append adds text to the end of the buffer.
Append Builds a Line
Three Append calls build one line piece by piece. ToString prints the finished line.
using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
sb.Append("Report");
sb.Append(" for ");
sb.Append("Monday");
Console.WriteLine(sb.ToString());
}
}Insert Adds the Comma
The pieces first spell Hello World with a space. Insert places a comma at index 5.
using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append(" ");
sb.Append("World");
sb.Insert(5, ",");
Console.WriteLine(sb.ToString());
}
}The Buffer Grows in Place
Length reports the character count in the buffer. The count grows after the second Append call.
using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
sb.Append("Hello");
Console.WriteLine(sb.Length);
sb.Append(" World");
Console.WriteLine(sb.ToString());
Console.WriteLine(sb.Length);
}
}Example
using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
sb.Append("Row ");
sb.Append(7);
sb.Append(" Seat ");
sb.Append(12);
Console.WriteLine(sb.ToString());
}
}Key points
- The System.Text namespace holds the StringBuilder type.
- A string never changes after it is created.
- A StringBuilder edits its buffer in place.
- Append adds text to the end of the buffer.
- Insert places text at a given index in the buffer.
- ToString reads the finished text out of the buffer.
In this example, the StringBuilder starts empty. Append adds the word Row and a space, then the number 7. Two more Append calls add the seat label and the number 12. ToString prints the finished line, Row 7 Seat 12.
Note
A StringBuilder suits code that builds long text in many small steps.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which StringBuilder method adds text to the end of the buffer?