English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C# StringBuilder

In C#, string types are immutable. This means that a string cannot be changed once it is created. For example, a new string "Hello World!" will occupy memory space on the heap. Now, by changing the initial string from "Hello World!" to "Hello World! from Tutorials Teacher", a new string object will be created on the memory heap instead of modifying the original string at the same memory address. If the original string is changed multiple times through replacement, appending, deleting, or inserting a new string at the original string, this behavior will affect performance.

Memory allocation of string objects

To solve this problem, C# introduced StringBuilder in the System.Text namespace. StringBuilder does not create a new object in memory, but dynamically expands memory to accommodate the modified string.

Memory allocation of StringBuilder objects

Create a StringBuilder object

You can create an object of the StringBuilder class using the new keyword and pass the initial string. The following example demonstrates the creation of a StringBuilder object.

using System.Text; //Introduction
            
StringBuilder sb = new StringBuilder(); //The string will be appended later
//or
StringBuilder sb = new StringBuilder("Hello World!");

Alternatively, you can also use the overloaded constructor to specify the maximum capacity of the StringBuilder object, as shown below.

StringBuilder sb = new StringBuilder(50); //The string will be appended later
//or
StringBuilder sb = new StringBuilder("Hello World!", 50);

In the above, C# allocates up to50 spaces. Once the specified capacity is reached, this capacity will automatically double. You can also use the capacity or length properties to set or retrieve the capacity of a StringBuilder object.

You can use a for loop to get or set the character at a specified index.

StringBuilder sb = new StringBuilder("Hello World!");
for(int i = 0; i < sb.Length; i++{
 Console.Write(sb[i]); // Output: Hello World!
}

Retrieve string from StringBuilder

StringBuilder is not a string. Use the ToString() method to retrieve a string from a StringBuilder object.

StringBuilder sb = new StringBuilder("Hello World!");
var greet = sb.ToString(); //Returns " Hello World!"

Add to StringBuilder/Append string

Use the Append() method to append a string to the end of the current StringBuilder object. If the StringBuilder does not contain any strings, it will add it. The AppendLine() method appends a newline character to the end of the string.

StringBuilder sb = new StringBuilder();
sb.Append("Hello ");
sb.AppendLine("World!");
sb.AppendLine("Hello C# ");
Console.WriteLine(sb);
Output:
Hello World!
Hello C#

Append formatted string to StringBuilder

Use the AppendFormat() method to format the input string to the specified format and then append it.

StringBuilder sbAmout = new StringBuilder("Your total amount is ");
sbAmout.AppendFormat("{0:C} ", 25);
Console.WriteLine(sbAmout);//Output: Your total amount is $25.00

Insert String into StringBuilder

Use the Insert() method to insert a string at the specified index of the StringBuilder object.

StringBuilder sb = new StringBuilder("Hello World!");
sb.Insert(5," C# "); 
Console.WriteLine(sb); //Output: Hello C# World!

Delete string in StringBuilder

Use the Remove() method to delete a string from the specified index to the specified length.

StringBuilder sb = new StringBuilder("Hello World!",50);
sb.Remove(6, 7);
Console.WriteLine(sb); //Output: Hello

Replace string in StringBuilder

Use the Replace() method to replace all occurrences of the specified string with the specified replacement string.

StringBuilder sb = new StringBuilder("Hello World!");
sb.Replace("World", "C# ");
Console.WriteLine(sb);//Output: Hello C#!
Points to Remember:
  1. StringBuilder is mutable.

  2. StringBuilder is faster than string when appending multiple string values.

  3. Use StringBuilder when you need to append three or more strings.

  4. Add or append a string to the StringBuilder object using the Append() method.

  5. Retrieve the string from the StringBuilder object using the ToString() method.