Using the StringBuilder Class in .NET

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.

Importing the System.Text Namespace

The StringBuilder class is found in the System.Text namespace. To avoid having to provide a fully qualified type name in your code, you can import the System.Text namespace:

using namespace System;
using namespace System::Text;
using System;
using System.Text;
Imports System.Text

Instantiating a StringBuilder Object

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.

StringBuilder^ myStringBuilder = gcnew StringBuilder("Hello World!");
StringBuilder myStringBuilder = new StringBuilder("Hello World!");
Dim myStringBuilder As 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.

StringBuilder^ myStringBuilder = gcnew StringBuilder("Hello World!", 25);
StringBuilder myStringBuilder = new StringBuilder("Hello World!", 25);
Dim myStringBuilder As 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;
myStringBuilder.Capacity = 25;
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 all occurrences of a specified character or string in the current StringBuilder with another specified character or string.

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.

StringBuilder^ myStringBuilder = gcnew StringBuilder("Hello World!");
myStringBuilder->Append(" What a beautiful day.");
Console::WriteLine(myStringBuilder);
// The example displays the following output:
//       Hello World! What a beautiful day.
StringBuilder myStringBuilder = new StringBuilder("Hello World!");
myStringBuilder.Append(" What a beautiful day.");
Console.WriteLine(myStringBuilder);
// The example displays the following output:
//       Hello World! What a beautiful day.
Dim myStringBuilder As New StringBuilder("Hello World!")
myStringBuilder.Append(" What a beautiful day.")
Console.WriteLine(myStringBuilder)
' The example displays the following output:
'       Hello World! What a beautiful day.

AppendFormat

The StringBuilder.AppendFormat method adds text to the end of the StringBuilder object. It supports the composite formatting feature (for more information, see Composite Formatting) by calling the IFormattable implementation of the object or objects to be formatted. Therefore, it accepts the standard format strings for numeric, date and time, and enumeration values, the custom format strings for numeric and date and time values, and the format strings defined for custom types. (For information about formatting, see Formatting Types.) 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 object.

int MyInt = 25;
StringBuilder^ myStringBuilder = gcnew StringBuilder("Your total is ");
myStringBuilder->AppendFormat("{0:C} ", MyInt);
Console::WriteLine(myStringBuilder);
// The example displays the following output:
//       Your total is $25.00
int MyInt = 25;
StringBuilder myStringBuilder = new StringBuilder("Your total is ");
myStringBuilder.AppendFormat("{0:C} ", MyInt);
Console.WriteLine(myStringBuilder);
// The example displays the following output:
//       Your total is $25.00
Dim MyInt As Integer = 25
Dim myStringBuilder As New StringBuilder("Your total is ")
myStringBuilder.AppendFormat("{0:C} ", MyInt)
Console.WriteLine(myStringBuilder)
' The example displays the following output:
'     Your total is $25.00  

Insert

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

StringBuilder^ myStringBuilder = gcnew StringBuilder("Hello World!");
myStringBuilder->Insert(6,"Beautiful ");
Console::WriteLine(myStringBuilder);
// The example displays the following output:
//       Hello Beautiful World!
StringBuilder myStringBuilder = new StringBuilder("Hello World!");
myStringBuilder.Insert(6,"Beautiful ");
Console.WriteLine(myStringBuilder);
// The example displays the following output:
//       Hello Beautiful World!
Dim myStringBuilder As New StringBuilder("Hello World!")
myStringBuilder.Insert(6, "Beautiful ")
Console.WriteLine(myStringBuilder)
' The example displays the following output:
'      Hello Beautiful World!

Remove

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 uses the Remove method to shorten a StringBuilder object.

StringBuilder^ myStringBuilder = gcnew StringBuilder("Hello World!");
myStringBuilder->Remove(5,7);
Console::WriteLine(myStringBuilder);
// The example displays the following output:
//       Hello
StringBuilder myStringBuilder = new StringBuilder("Hello World!");
myStringBuilder.Remove(5,7);
Console.WriteLine(myStringBuilder);
// The example displays the following output:
//       Hello
Dim myStringBuilder As New StringBuilder("Hello World!")
myStringBuilder.Remove(5, 7)
Console.WriteLine(myStringBuilder)
' The example displays the following output:
'       Hello

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 (?).

StringBuilder^ myStringBuilder = gcnew StringBuilder("Hello World!");
myStringBuilder->Replace('!', '?');
Console::WriteLine(myStringBuilder);
// The example displays the following output:
//       Hello World?
StringBuilder myStringBuilder = new StringBuilder("Hello World!");
myStringBuilder.Replace('!', '?');
Console.WriteLine(myStringBuilder);
// The example displays the following output:
//       Hello World?
Dim myStringBuilder As New StringBuilder("Hello World!")
myStringBuilder.Replace("!"c, "?"c)
Console.WriteLine(myStringBuilder)
' The example displays the following output:
'       Hello World?

Converting a StringBuilder Object to a String

You must convert the StringBuilder object to a String object before you can pass the string represented by the StringBuilder object to a method that has a String parameter or display it in the user interface. You do this conversion by calling the StringBuilder.ToString method. The following example calls a number of StringBuilder methods and then calls the StringBuilder.ToString() method to display the string.

using System;
using System.Text;

public class Example
{
   public static void Main()
   {
      StringBuilder sb = new StringBuilder();
      bool flag = true;
      string[] spellings = { "recieve", "receeve", "receive" };
      sb.AppendFormat("Which of the following spellings is {0}:", flag);
      sb.AppendLine();
      for (int ctr = 0; ctr <= spellings.GetUpperBound(0); ctr++) {
         sb.AppendFormat("   {0}. {1}", ctr, spellings[ctr]);
         sb.AppendLine();
      }
      sb.AppendLine();
      Console.WriteLine(sb.ToString());
   }
}
// The example displays the following output:
//       Which of the following spellings is True:
//          0. recieve
//          1. receeve
//          2. receive
Imports System.Text

Module Example
    Public Sub Main()
        Dim sb As New StringBuilder()
        Dim flag As Boolean = True
        Dim spellings() As String = {"recieve", "receeve", "receive"}
        sb.AppendFormat("Which of the following spellings is {0}:", flag)
        sb.AppendLine()
        For ctr As Integer = 0 To spellings.GetUpperBound(0)
            sb.AppendFormat("   {0}. {1}", ctr, spellings(ctr))
            sb.AppendLine()
        Next
        sb.AppendLine()
        Console.WriteLine(sb.ToString())
    End Sub
End Module
' The example displays the following output:
'       Which of the following spellings is True:
'          0. recieve
'          1. receeve
'          2. receive

See also