#71 – StringBuilder Capacity

You can use a StringBuilder object without worrying about how much memory it has allocated internally for the strings that it stores.  The StringBuilder class will automatically allocate enough memory to store the strings that it is working with.

The Capacity property indicates the the maximum number of characters that can be stored in a StringBuilder object.  If an operation results in a string requiring more memory, additional memory will automatically be allocated and Capacity will be increased.

The Length property indicates the length of the string stored in the StringBuilder object.

By default, Capacity starts out at 16 and is doubled whenever more characters are required for a string.

 StringBuilder sb1 = new StringBuilder();    // Len=0, Cap=16
 sb1.Append("1234567890123456");             // Len=16, Cap=16
 sb1.Append("z");                            // Len=17, Cap=32
 sb1.Append("1234567890123456");             // Len=33, Cap=64

You can also explicitly specify capacity when you instantiate a StringBuilder:

 StringBuilder sb2 = new StringBuilder(100);
Advertisements

#70 – The StringBuilder Class

For more efficient string manipulation, you can use the StringBuilder class, which has methods that allow you to modify its internal character data without allocating a new string for each operation.

A StringBuilder instance wraps a single Unicode string and allows you to modify that string in different ways.

StringBuilder can be found in the System.Text namespace.

Constructing a StringBuilder:

 StringBuilder sb1 = new StringBuilder();    // Empty string
 StringBuilder sb2 = new StringBuilder("Sean");

Modifying internal string:

 sb2.Append(" was here");
 sb2.AppendFormat(" on {0:d}", DateTime.Today);
 sb2.Replace("Sean", "Kilroy");
 sb2.Insert(0, "Mr. ");          // Insert at start of string

Other things that you can do with a StringBuilder object:

 char third = sb2[2];            // 3rd character
 string s = sb2.ToString();      // Convert to string
 int len = sb2.Length;           // # chars