C# StringBuilder:

A String is immutable, meaning String cannot be changed once created. For example, new string "Hello World!!" will occupy a memory space on the heap. Now, by changing the initial string "Hello World!!" to "Hello World!! from Tutorials Teacher" will create a new string object on the memory heap instead of modifying the initial string at the same memory address. This behaviour will hinder the performance if the same string changes multiple times by replacing, appending, removing or inserting new strings in the initial string.

Memory allocation for String
Memory allocation for String

To solve this problem, C# introduced StringBuilder. StringBuilder is a dynamic object that allows you to expand the number of characters in the string. It doesn't create a new object in the memory but dynamically expands memory to accommodate the modified string.

Memory allocation for StringBuilder
Memory allocation for StringBuilder

Initialization:

StringBuilder can be initialized the same way as class.

Example: StringBuilder

StringBuilder sb = new StringBuilder();
            
//or

StringBuilder sb = new StringBuilder("Hello World!!");

You can give an initial capacity of characters by passing an int value in the constructor. For example, the following will allocate memory of 50 characters sequentially on the memory heap. The memory allocation automatically expands once it reaches the capacity.

Example: StringBuilder

StringBuilder sb = new StringBuilder(50);

//or

StringBuilder sb = new StringBuilder("Hello World!!",50);

Important Methods of StringBuilder:

Method Name Description
StringBuilder.Append(valueToAppend) Appends the passed values to the end of the current StringBuilder object.
StringBuilder.AppendFormat() Replaces a format specifier passed in a string with formatted text.
StringBuilder.Insert(index, valueToAppend) Inserts a string at the specified index of the current StringBuilder object.
StringBuilder.Remove(int startIndex, int length) Removes the specified number of characters from the given starting position of the current StringBuilder object.
StringBuilder.Replace(oldValue, newValue) Replaces characters with new characters.

Append()/AppendLine():

Use Append method of StringBuilder to add or append a string to StringBuilder. AppendLine() method appends the string with a newline at the end.

Example: Append()

StringBuilder sb = new StringBuilder("Hello ",50);

sb.Append("World!!");
sb.AppendLine("Hello C#!");
sb.AppendLine("This is new line.");

Console.WriteLine(sb);

Output:
Hello World!! Hello C#!.
This is new line.
 
Note : StringBuilder performs faster than string when concatenating multiple strings. Use StringBuilder if you want to append more than three-four string. Appending two or three string is more efficient than using StringBuilder.

AppendFormat():

Use AppendFormat method to format input string into specified format and then append it.

Example: AppendFormat()
            
StringBuilder amountMsg = new StringBuilder("Your total amount is ");
amountMsg.AppendFormat("{0:C} ", 25);

Console.WriteLine(amountMsg);

Output:
Your total amount is $ 25.00

Insert():

The Insert() method inserts the string at specified index in StringBuilder.

Example: Insert()

StringBuilder sb = new StringBuilder("Hello World!!",50);
sb.Insert(5," C#");

Console.WriteLine(sb);

Output:
Hello C# World!!

Remove():

The Remove() method removes the string at specified index with specified length.

Example: Remove()

StringBuilder sb = new StringBuilder("Hello World!!",50);
sb.Remove(6, 7);

Console.WriteLine(sb);

Output:
Hello

Replace():

The Replace() method replaces all occurance of a specified string with a specified replacement string.

Example: Replace()

StringBuilder sb = new StringBuilder("Hello World!!",50);
sb.Replace("World", "C#");

Console.WriteLine(sb);

Output:
Hello C#!!

Indexer:

You can use indexer with StringBuilder to get or set a character at specified index. The following example uses indexer to get all the characters of StringBuilder using for loop.

Example: StringBuilder as Indexer

StringBuilder sb = new StringBuilder("Hello World!!");

for(int i=0; i< sb.Length; i++)
        Console.Write(sb[i]);

Output:
Hello World!!

ToString():

Use ToString() method to get string from StringBuilder.

Example: ToString()

StringBuilder sb = new StringBuilder("Hello World!!");

string str = sb.ToString(); // "Hello World!!"

Points to Remember :

  1. StringBuilder is mutable.
  2. StringBuilder performs faster than string when appending multiple string values.
  3. Initialize StringBuilder as class e.g. StringBuilder sb = new StringBuilder()
  4. Use StringBuilder when you need to append more than three or four strings.
  5. Use Append() method to add or append strings with StringBuilder.
  6. Use ToString() method to get the string from StringBuilder.