CodeGym /Courses /C# SELF /StringBuilder Class for Working with Strings

StringBuilder Class for Working with Strings

C# SELF
Level 9 , Lesson 5
Available

1. Introduction

Just a reminder, strings in C# are immutable (immutable). That means after you create a string, you can't change it: any operation that looks like it "changes" a string actually creates a new string in memory.

For example, when you write:

string hello = "Hello";
hello += " world!"; // Looks like hello changed, but actually a new object was created!

The hello variable now points to a new object, and the old one (if it's not used anywhere) will eventually get deleted by the garbage collector. If you do stuff like this in a loop a bunch of times, you can get a "pileup" in RAM and your performance can tank. This really hits hard if you're joining thousands or millions of strings: every step creates a new string, copies all its characters, old objects hang around until GC, and suddenly your app starts lagging.

And that's where the hero of this lecture comes in — StringBuilder.


using System.Text; // ← don't forget this!
StringBuilder sb = new StringBuilder("Hello");
sb.Append(" world!"); // Now the string changes fast and efficiently

Meet StringBuilder

StringBuilder is a class from the System.Text namespace. Its job is to efficiently create and build big strings, changing their contents without constantly making new objects.

Analogy:
If a string (string) is like a piece of a mosaic that you can only swap out completely, then StringBuilder is like a magnetic board where you can stick and remove those pieces as much as you want, without getting a new board every time you want to add or remove a piece.

When should you use StringBuilder?

  • If you're changing a string a bunch of times (especially in a loop).
  • If you're building text from a lot of little pieces.
  • If you care about speed and memory usage.

When should you NOT use it?

  • If you only have 1-2 simple string operations — a regular string is easier and more readable.
  • If you actually want (for some reason) to keep every single state of the string.

2. Creating and Basic Operations with StringBuilder

Adding the Namespace

Getting started is easy: just don't forget to add the namespace.

using System.Text;// ← don't forget this!

Ways to Create a New StringBuilder


StringBuilder sb1 = new StringBuilder();            // Empty
StringBuilder sb2 = new StringBuilder("Start");     // With initial text
StringBuilder sb3 = new StringBuilder(100);         // With space for 100 chars

Main Methods

var sb = new StringBuilder("Begin");
sb.Append(" + added new text"); 			// Add to the end
sb.AppendLine(" (and this with a line break)"); 	// Add with \n
sb.Insert(0, "Start: "); 						// Insert at position 0
sb.Remove(0, 7); 								// Remove 7 chars from position 0
sb.Replace("text", "STRING"); 					// Replace all "text" with "STRING"
string result = sb.ToString(); 					// Get the final string

3. Efficiency of StringBuilder

Example: Performance Comparison

Let's say you need to build a string from 10,000 numbers in a row (like, maybe you were told to print all your classmates' numbers):

Naive approach (string)

string text = "";
for (int i = 0; i < 10000; i++)
{
    text += i + " "; // Every step creates a new string!
}
Console.WriteLine(text.Substring(0, 100) + "..."); // To keep output short

Optimal approach (StringBuilder)

var sb = new StringBuilder();
for (int i = 0; i < 10000; i++)
{
    sb.Append(i).Append(' '); // You can chain them!
}
Console.WriteLine(sb.ToString().Substring(0, 100) + "...");

What's the difference?
The first way will run noticeably slower and can eat up way more memory. The second — is fast and doesn't hog your RAM.

4. Most Popular StringBuilder Methods

Append — adds a string or another type (auto converts to string):

sb.Append("text");
sb.Append(123); // 123 turns into "123"
sb.Append('!'); // A char

AppendLine — adds a string + a new line character:

sb.AppendLine("string"); // Adds "string\n"

Insert — inserts a string at a certain position:

sb.Insert(0, "Hello, "); // Insert at the start

Remove — removes several characters:

sb.Remove(3, 4); // Removes 4 chars starting from position 3

Replace — replaces all occurrences of a substring or char:

sb.Replace("old", "new");
sb.Replace('a', 'A');

ToString — returns the finished string.

Trimming the String

Unlike string, a StringBuilder object can have its length set to a new value. The string will be trimmed to that length.

sb.Length = 10; // Everything after the 10th char — gone!

5. Special Features and Common Mistakes

Why ToString() Matters

While you're working with StringBuilder, what you have "in your hands" isn't a string, but a special object. A lot of methods (like Console.WriteLine) are cool with it, because it can auto-convert to a string, but sometimes you might get a surprise — if you accidentally compare it to a regular string or do something like:

if (sb == "Hello") { ... } // Oops! This won't work, even if sb contains "Hello"

The result will be false: you're comparing objects of different types, not strings.

The right way:

if (sb.ToString() == "Hello") { ... }

Mutability

Unlike string, StringBuilder is mutable! One object can change its contents as many times as you want, which is what gives you the speed boost.

Don't forget to call ToString() at the end of working with the object, or you'll get a weird text like System.Text.StringBuilder instead of your string.

Buffer Size and Resizing

Inside, StringBuilder keeps a char array. If you know ahead of time that you're gonna "cook up" a really long string, you can pass the expected length to the constructor — that'll make things a bit faster.

var bigBuilder = new StringBuilder(50000); // Expecting 50 thousand chars

But if you guessed wrong — no worries! StringBuilder will expand the buffer itself if needed, it'll just be a bit slower.

Out of Memory?

Theoretically, if you totally lose control and add billions of chars, you can hit OutOfMemoryException, but for real-life tasks this almost never happens.

2
Task
C# SELF, level 9, lesson 5
Locked
Modifying a string using StringBuilder methods
Modifying a string using StringBuilder methods
2
Task
C# SELF, level 9, lesson 5
Locked
Creating a List of Numbers Using StringBuilder
Creating a List of Numbers Using StringBuilder
1
Survey/quiz
Working with Strings, level 9, lesson 5
Unavailable
Working with Strings
Advanced string handling
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION