Use of StringBuilder with Examples
.NET String object is immutable. It means every time you use one of the String class methods, 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.
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.
System.Text.StringBuilder builder = new System.Text.StringBuilder("Mahesh Chand");
builder.Append(", ");
builder.Append("Chris Love");
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.
System.Text.StringBuilder numbers = new System.Text.StringBuilder();
// Create a string of 1000 numbers from 0 to 999
// separated by a comma and space
for (int counter = 0; counter <= 999; counter++)
{
numbers.Append(counter);
numbers.Append(", ");
}
Console.WriteLine(numbers);
Listing 2.
The output of Listing 2 looks like Figure 1.
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.
// Create a string and concatenate 10 strings
// Using + operator
string str = string.Empty;
DateTime startTime = DateTime.Now;
for (int i = 0; i < 10; i++)
{
str += i.ToString();
}
TimeSpan ts = DateTime.Now - startTime;
Console.WriteLine($"Execution time (10) using + operator: {ts.TotalMilliseconds}");
// Concatenation using StringBuilder
System.Text.StringBuilder builder = new System.Text.StringBuilder();
startTime = DateTime.Now;
for (int i = 0; i < 10; i++)
{
builder.Append(i.ToString());
}
ts = DateTime.Now - startTime;
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 than 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.
System.Text.StringBuilder builder = new System.Text.StringBuilder(); builder.Capacity = 1000;
OR
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.
- System.Text.StringBuilder builder = new System.Text.StringBuilder("Mahesh Chand");
- 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.
- int price = 45;
- System.Text.StringBuilder bookPrice = new System.Text.StringBuilder("Book price:");
- bookPrice.AppendFormat("{0:C} ", price);
- Console.WriteLine(bookPrice);
Insert a 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 the Insert method to insert two items starting at the 0th and 10th positions.
System.Text.StringBuilder builder = new System.Text.StringBuilder("Mahesh Chand");
builder.Append(", ");
builder.Append("Chris Love");
builder.Append(", Praveen Kumar");
builder.Insert(0, "Raj Kumar, ");
builder.Insert(10, 900);
builder.Append(", ");
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.
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.
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.