Export (0) Print
Expand All

Using the StringBuilder Class in the .NET Framework

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.

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

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 = 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;

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.

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.

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 = 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.

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 in the .NET Framework.) 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 = new StringBuilder("Your total is ");
MyStringBuilder.AppendFormat("{0:C} ", MyInt);
Console.WriteLine(MyStringBuilder);
// The example displays the following output: 
//       Your total is $25.00      

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 = new StringBuilder("Hello World!");
MyStringBuilder.Insert(6,"Beautiful ");
Console.WriteLine(MyStringBuilder);
// The example displays the following output: 
//       Hello Beautiful World!

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 = new StringBuilder("Hello World!");
MyStringBuilder.Remove(5,7);
Console.WriteLine(MyStringBuilder);
// The example displays the following output: 
//       Hello

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 = new StringBuilder("Hello World!");
MyStringBuilder.Replace('!', '?');
Console.WriteLine(MyStringBuilder);
// The example displays the following output: 
//       Hello World?

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
Show:
© 2014 Microsoft