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());
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,
27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,

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 .