CSharp - String StringBuilder class


StringBuilder class from System.Text namespace represents an editable string.

With a StringBuilder, you can Append, Insert, Remove, and Replace substrings without replacing the whole StringBuilder.

You can use initial string value to create new StringBuilder object.

You can also set starting size for its internal capacity which is default to 16 characters.

If you go above this, StringBuilder automatically resizes its internal structures to accommodate up to its maximum capacity which is default to int.MaxValue.

The following code shows how to use StringBuilder to build up a long string by repeatedly calling Append.

This approach is more efficient than concatenating ordinary string types:

To get the final result, call ToString():


using System;
using System.Text;

class MainClass/* ww w .  j  ava2 s  .  c o m*/
    public static void Main(string[] args)
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 50; i++)
            sb.Append(i + ",");




AppendLine performs an Append and adds a new line sequence ( "\r\n" in Windows).

AppendFormat accepts a composite format string, just like String.Format.

To clear the contents of a StringBuilder, either instantiate a new one or set its Length to zero.