StringBuilder and String Concatenation

C# String Builder represented by the StringBuilder class in c# is used to concatenate strings in C# and provides string modifications methods including StringBuilder.Append(), StringBuilder.Remove(), and StringBuilder.Replace().

Use of StringBuilder with Examples

 
.NET String object in immutable. It means every time you use one of the String class methods, a memory space is allocated for that new string object in computer memory. For multiple or repetitive string modifications, it becomes a costly affair.
 
For repetitive string modifications, .NET provides the System.Text.StringBuilder class. The following table lists StringBuilder methods and their description. MethodDescription StringBuilder.AppendAppends string to the end of the current StringBuilder.
 

Method 

Description

StringBuilder.Append

Appends string to the end of the current StringBuilder.

StringBuilder.AppendFormat

Replaces a format specifier passed in a string with formatted text.

StringBuilder.Insert

Inserts a string or object into the specified index of the current StringBuilder.

StringBuilder.Remove

Removes a specified number of characters from the current StringBuilder.

StringBuilder.Replace

Replaces a specified character at a specified index.

 
The StringBuilder class is defined in the System.Text namespace. You must either import this namespace in your class or reference it directly in the object instantiation. 
  1. using System.Text;  
The StringBuilder constructor can take a string or can be no arguments.
 
The following code snippet in Listing 1 creates a StringBuilder and appends 3 strings. 
  1. System.Text.StringBuilder builder = new System.Text.StringBuilder("Mahesh Chand");  
  2. builder.Append(", ");  
  3. builder.Append("Chris Love");  
  4. builder.Append(", Praveen Kumar");  
Listing 1.
 
The following code example in Listing 2 creates a string of numbers from 0 to 999 and each number is separated by a comma and a space. 
  1. System.Text.StringBuilder numbers = new System.Text.StringBuilder();  
  2. // Create a string of 1000 numbers from 0 to 999  
  3. // separated by a comma and space  
  4. for (int counter = 0; counter <= 999; counter++)  
  5. {  
  6.     numbers.Append(counter);  
  7.     numbers.Append(", ");  
  8. }  
  9. Console.WriteLine(numbers);  
Listing 2.
 
The output of Listing 2 looks like Figure 1.
 
C# StringBuilder 
 
Figure 1.
 

StringBuilder and Performance

 
The StringBuilder can improve the performance of your code if string concatenation is needed more than a few times.
 
The code example in Listing 3 concatenates 10 strings. In the first part of the code, it uses a normal + operator to concatenate strings and the second part of the code uses a StringBuilder. 
  1. // Create a string and concatenate 10 strings   
  2. // Using + operator  
  3. string str = string.Empty;  
  4. DateTime startTime = DateTime.Now;    
  5. for (int i = 0; i < 10; i++)  
  6. {  
  7.     str += i.ToString();  
  8. }              
  9. TimeSpan ts = DateTime.Now - startTime;  
  10. Console.WriteLine($"Execution time (10) using + operator: {ts.TotalMilliseconds}");  
  11.   
  12. // Concatenation using StringBuilder        
  13. System.Text.StringBuilder builder = new System.Text.StringBuilder();  
  14. startTime = DateTime.Now;  
  15. for (int i = 0; i < 10; i++)  
  16. {  
  17.     builder.Append(i.ToString());  
  18. }  
  19. ts = DateTime.Now - startTime;  
  20. Console.WriteLine($"Execution time (10) using SB: {ts.TotalMilliseconds}");  
Listing 3.
 
The result of Listing 3 looks like the following in milliseconds. As you can see, StringBuilder is much faster that string methods.
 
Execution time (10) using + operator: 2.6742
Execution time (10) using SB: 0.0051
 
Now, let’s try the same operation 1000 times by changing the for loop from 0 to 1000.
 
The new results look like the following.
 
Execution time (1000) using + operator: 4.5812
Execution time (1000) using SB: 0.1177
 

StringBuilder Capacity

 
The size of StringBuilder expands dynamically when more items are added to the object. However, you can set its maximum number of characters by setting its Capacity property. You can also pass a StringBuilder capacity as a constructor argument. 
  1. System.Text.StringBuilder builder = new System.Text.StringBuilder(); builder.Capacity = 1000;  
OR 
  1. System.Text.StringBuilder builder = new System.Text.StringBuilder(1000);  

Modifying StringBuilder String

 
StringBuilder class provides the following methods to modify its value.
 

Method Name

Description

StringBuilder.Append

Appends information to the end of the current StringBuilder.

StringBuilder.AppendFormat

Replaces a format specifier passed in a string with formatted text.

StringBuilder.Insert

Inserts a string or object into the specified index of the current StringBuilder.

StringBuilder.Remove

Removes a specified number of characters from the current StringBuilder.

StringBuilder.Replace

Replaces a specified character at a specified index.

 

Append string in StringBuilder

 
Append methods append a string or an object to an existing StringBuilder string. The space is allocated dynamically and expands when new strings are added to the StringBuilder. The following code snippet creates a StringBuilder and appends a string. 
  1. System.Text.StringBuilder builder = new System.Text.StringBuilder("Mahesh Chand");  
  2. builder.Append("Chris Love");  

Format string in StringBuilder

 
AppendFormat method formats string of StringBuilder. It supports standard formats available in .NET. The following code snippet formats an integer to a decimal.
  1. int price = 45;  
  2. System.Text.StringBuilder bookPrice = new System.Text.StringBuilder("Book price:");  
  3. bookPrice.AppendFormat("{0:C} ", price);  
  4. Console.WriteLine(bookPrice);  

Insert string at a specified position in a StringBuilder

 
The Insert method adds a string or object at a specified position in the current string. The following example uses Insert method to insert two items starting at 0th and 10th positions. 
  1. System.Text.StringBuilder builder = new System.Text.StringBuilder("Mahesh Chand");  
  2. builder.Append(", ");  
  3. builder.Append("Chris Love");  
  4. builder.Append(", Praveen Kumar");  
  5. builder.Insert(0, "Raj Kumar, ");  
  6. builder.Insert(10, 900);  
  7. builder.Append(", ");  
  8. Console.WriteLine(builder);  

Remove string from a StringBuilder

 
You can use the Remove method to remove a specified number of characters from the current StringBuilder object, beginning at a specified zero-based index. The following example removes 3 characters from the StringBuilder starting at the 0th position. 
  1. builder.Remove(0, 3);  

Replace string in StringBuilder

 
The Replace method can be used to replace characters within the StringBuilder object with another specified character. The following example replaces a comma with a colon in a StringBuilder. 
  1. builder.Replace(','':');  
 

Summary

C# StringBuilder is useful when dealing with string concatenation and modification operations. In this article and code examples, we saw how to work with StringBuilder to work with strings.