C# StringBuilder
StringBuilder
In the String Methods chapter, you learned that methods like Replace() do not change the original string. They return a new string. The + operator also creates a new string every time you use it. In C#, a string cannot be changed after it is created.
A StringBuilder is text that can be changed. You can add, insert, replace and remove text, and C# keeps changing the same text. Think of it like a document that you keep editing, instead of writing a new copy for every change.
To use StringBuilder, add this line at the top of your program, below using System;:
Example
// Include the namespace that holds StringBuilder
using System.Text;
Now you can create a StringBuilder and add text to it:
Example
StringBuilder sb = new StringBuilder("Hello");
sb.Append(" World");
Console.WriteLine(sb);
Example explained
new StringBuilder("Hello")creates a StringBuilder with the text"Hello".sb.Append(" World")adds" World"to the end of the text.Console.WriteLine(sb)prints the textHello World.
Add Text with Append()
The Append() method adds text to the end. You can call it as many times as you like, and it also works with numbers.
Empty parentheses, new StringBuilder(), create an empty StringBuilder:
Example
StringBuilder sb = new StringBuilder();
sb.Append("Liam");
sb.Append(" has ");
sb.Append(3);
sb.Append(" apples");
Console.WriteLine(sb);
Just like a string, a StringBuilder has a Length property, which returns the number of characters:
Example
StringBuilder sb = new StringBuilder("Hello");
sb.Append(" World");
Console.WriteLine(sb.Length); // 11
Insert, Replace and Remove
A StringBuilder can also change text in the middle. Remember that positions start at 0, just like in Access Strings:
Insert(position, text)inserts text at a positionReplace(oldText, newText)replaces everyoldTextwithnewTextRemove(position, count)removes a number of characters (count), starting at a position
Example
StringBuilder sb = new StringBuilder("I like cats");
sb.Insert(7, "black "); // I like black cats
sb.Replace("cats", "dogs"); // I like black dogs
sb.Remove(7, 6); // I like dogs
Console.WriteLine(sb);
Remove(7, 6) removes 6 characters, starting at position 7. That is the text "black " (5 letters and a space).
Convert to a String
Use ToString() to turn a StringBuilder into a normal string. You need this when you want to store the text in a string variable, or use string methods like ToUpper():
Example
StringBuilder sb = new StringBuilder("hello");
sb.Append(" world");
string text = sb.ToString();
Console.WriteLine(text.ToUpper()); // HELLO WORLD
String vs. StringBuilder
Use a string for text that does not change, like a name or a message.
Use a StringBuilder when you change the text many times. It is faster, because C# does not have to create a new string for every change.