
.NET 1.1+The StringBuilder Class (2)
Creating strings with the use of multiple concatenation operations can lead to low performance and wasteful memory usage. The StringBuilder class allows strings to be created and updated without the problems caused by the immutability of the String class.
StringBuilder Properties
Capacity
The Capacity property can be read to obtain the current character capacity of the StringBuilder. You can also set this property to increase or decrease the capacity and associated memory allocation. You may not reduce the capacity to a value lower than the overall length of the object's contents.
StringBuilder sb = new StringBuilder("Hello, world!");
Console.WriteLine(sb.Capacity);
sb.Capacity = 13;
Console.WriteLine(sb.Capacity);
/* OUTPUT
16
13
*/
MaxCapacity
The maximum capacity for a StringBuilder may only be set using a constructor. You can, however, obtain the maximum capacity by reading the MaxCapacity property.
StringBuilder sb = new StringBuilder("Hello, world!");
Console.WriteLine(sb.MaxCapacity); // Outputs "2147483647"
Length
The Length property can be read to obtain the current length of a StringBuilder's contents. You may also set this property to change the length. Reducing the length causes the contents to be truncated. Increasing the length pads the end of the StringBuilder with null characters.
StringBuilder sb = new StringBuilder("Hello, world!");
sb.Length = 5;
Console.WriteLine(sb); // Outputs "Hello"
Chars
The Chars property provides direct access to each of the characters held within the StringBuilder. This property is an indexer so when accessed using C#, the property name is not used. As with standard strings, the indexer can be used to read any single character. Unlike with the String class, you can also change the value of individual characters by assigning a value.
StringBuilder sb = new StringBuilder("Hello, world!");
sb[12] = '?';
Console.WriteLine(sb); // Outputs "Hello, world?"
Modifying StringBuilder Contents
The key benefits of the StringBuilder class are seen when modifying the contained string. In this section we will examine six methods that allow characters to be appended, inserted, modified and deleted.
Append
The Append method can be used to add characters to the end of the contents of a StringBuilder. In many cases a string will be appended. However, the Append method includes many overloaded versions, each appending a string representation of a value or object.
string player = "Bob";
int points = 1234;
TimeSpan duration = new TimeSpan(1, 30, 0);
StringBuilder sb = new StringBuilder();
sb.Append(player);
sb.Append(" scored ");
sb.Append(points);
sb.Append(" points in ");
sb.Append(duration);
sb.Append(".");
Console.WriteLine(sb); // Outputs "Bob scored 1234 points in 01:30:00."
NB: The above code is for example purposes only. Such simple concatenation could be achieved more efficiently using string concatenation or the String.Format method.
25 October 2009