Using the StringBuilder Class

The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

You can create a new instance of the StringBuilder class by initializing your variable with one of the overloaded constructor methods, as illustrated in the following example.

Dim MyStringBuilder As New StringBuilder("Hello World!")
[C#]
StringBuilder MyStringBuilder = new StringBuilder("Hello World!");

Setting the Capacity and Length

Although the StringBuilder is a dynamic object that allows you to expand the number of characters in the string that it encapsulates, you can specify a value for the maximum number of characters that it can hold. This value is called the capacity of the object and should not be confused with the length of the string that the current StringBuilder holds. For example, you might create a new instance of the StringBuilder class with the string "Hello", which has a length of 5, and you might specify that the object has a maximum capacity of 25. When you modify the StringBuilder, it does not reallocate size for itself until the capacity is reached. When this occurs, the new space is allocated automatically and the capacity is doubled. You can specify the capacity of the StringBuilder class using one of the overloaded constructors. The following example specifies that the MyStringBuilder object can be expanded to a maximum of 25 spaces.

Dim MyStringBuilder As New StringBuilder("Hello World!", 25) 
[C#]
StringBuilder MyStringBuilder = new StringBuilder("Hello World!", 25);  

Additionally, you can use the read/write Capacity property to set the maximum length of your object. The following example uses the Capacity property to define the maximum object length.

MyStringBuilder.Capacity = 25
[C#]
MyStringBuilder.Capacity = 25;

The EnsureCapacity method can be used to check the capacity of the current StringBuilder. If the capacity is greater than the passed value, no change is made; however, if the capacity is smaller than the passed value, the current capacity is changed to match the passed value.

The Length property can also be viewed or set. If you set the Length property to a value that is greater than the Capacity property, the Capacity property is automatically changed to the same value as the Length property. Setting the Length property to a value that is less than the length of the string within the current StringBuilder shortens the string.

Modifying the StringBuilder String

The following table lists the methods you can use to modify the contents of a StringBuilder.

Method name Use
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

The Append method can be used to add text or a string representation of an object to the end of a string represented by the current StringBuilder. The following example initializes a StringBuilder to "Hello World" and then appends some text to the end of the object. Space is allocated automatically as needed.

Dim MyStringBuilder As New StringBuilder("Hello World!")
MyStringBuilder.Append(" What a beautiful day.")
Console.WriteLine(MyStringBuilder)
[C#]
StringBuilder MyStringBuilder = new StringBuilder("Hello World!");
MyStringBuilder.Append(" What a beautiful day.");
Console.WriteLine(MyStringBuilder);

This example displays Hello World! What a beautiful day. to the console.

AppendFormat

The AppendFormat method adds text to the end of the StringBuilder, but also implements the IFormattable interface and therefore accepts the standard format strings described in the formatting section. You can use this method to customize the format of variables and append those values to a StringBuilder. The following example uses the AppendFormat method to place an integer value formatted as a currency value at the end of a StringBuilder.

Dim MyInt As Integer = 25
Dim MyStringBuilder As New StringBuilder("Your total is ")
MyStringBuilder.AppendFormat("{0:C} ", MyInt)
Console.WriteLine(MyStringBuilder)
[C#]
int MyInt = 25; 
StringBuilder MyStringBuilder = new StringBuilder("Your total is ");
MyStringBuilder.AppendFormat("{0:C} ", MyInt);
Console.WriteLine(MyStringBuilder);

This example displays Your total is $25.00 to the console.

Insert

The Insert method adds a string or object to a specified position in the current StringBuilder. The following example uses this method to insert a word into the sixth position of a StringBuilder.

Dim MyStringBuilder As New StringBuilder("Hello World!")
MyStringBuilder.Insert(6, "Beautiful ")
Console.WriteLine(MyStringBuilder)
[C#]
StringBuilder MyStringBuilder = new StringBuilder("Hello World!");
MyStringBuilder.Insert(6,"Beautiful ");
Console.WriteLine(MyStringBuilder);

This example displays Hello Beautiful World! to the console.

Remove

You can use the Remove method to remove a specified number of characters from the current StringBuilder, beginning at a specified zero-based index. The following example uses the Remove method to shorten a StringBuilder.

Dim MyStringBuilder As New StringBuilder("Hello World!")
MyStringBuilder.Remove(5, 7)
Console.WriteLine(MyStringBuilder)
[C#]
StringBuilder MyStringBuilder = new StringBuilder("Hello World!");
MyStringBuilder.Remove(5,7);
Console.WriteLine(MyStringBuilder);

This example displays Hello to the console.

Replace

The Replace method can be used to replace characters within the StringBuilder object with another specified character. The following example uses the Replace method to search a StringBuilder object for all instances of the exclamation point character (!) and replace them with the question mark character (?).

Dim MyStringBuilder As New StringBuilder("Hello World!")
MyStringBuilder.Replace("!"c, "?"c)
Console.WriteLine(MyStringBuilder)
[C#]
StringBuilder MyStringBuilder = new StringBuilder("Hello World!");
MyStringBuilder.Replace('!', '?');
Console.WriteLine(MyStringBuilder);

This example displays Hello World? to the console.

See Also

Basic String Operations | System.Text.StringBuilder