C# - StringBuilder Class

StringBuilder Class

The StringBuilder class (System.Text namespace) represents a mutable (editable) string. With a StringBuilder, you can Append, Insert, Remove, and Replace substrings without replacing the whole StringBuilder.

StringBuilder’s constructor optionally accepts an initial string value, as well as a starting size for its internal capacity (default is 16 characters). If you go above this, StringBuilder automatically resizes its internal structures to accommodate (at a slight performance cost) up to its maximum capacity (default is int.MaxValue).

A popular use of StringBuilder is to build up a long string by repeatedly calling Append. This approach is much more efficient than repeatedly concatenating ordinary string types:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 50; i++) sb.Append (i + ",");

To get the final result, call ToString():

Console.WriteLine (sb.ToString());

The StringBuilder class contains some other important methods, which are described in the following table.

Method Description
Append Appends the string representation of a specified object to the end of this instance.
AppendFormat Appends a formatted string, which contains zero or more format specifiers, to this instance. Each format specification is replaced by the string representation of a corresponding object argument.
AppendLine Appends the default line terminator, or a copy of a specified string and the default line terminator, to the end of this instance.
CopyTo Copies the characters from a specified segment of this instance to a specified segment of a destination Char array.
Insert Inserts the string representation of a specified object into this instance at a specified character position.
Remove Removes the specified range of characters from this instance.
Replace Replaces all occurrences of a specified character or string in this instance with another specified character or string.
ToString Converts the value of a StringBuilder to a String .