C# StringBuilder class

Updated on     Kisan Patel

The System.Text.StringBuilder class is very similar to the System.String class. but the difference is that StringBuilder class is mutable (mutable means you can modified state of objects by operations).

Unlike in the string class, you must first call the constructor of a StringBuilder to instantiate its object.

string str = "This is a string!";
StringBuilder sb = new StringBuilder("This is the StringBuilder!");

StringBuilder is somewhat similar to ArrayList and other collections in the way that it grows automatically as the size of the string it contains changes. Hence, the capacity of a StringBuilder may be different from its Length. Some of the more common properties and methods of the StringBuilder class are listed in the following table:

StringBuilder.Length Gets the number of characters that the StringBuilder object contains.
StringBuilder.Capacity Gets the current capacity of the StringBuilder object.
StringBuilder.Append(string) Appends the string representation of the specified object at the end of this StringBuilder instance. The methos has a number of overloaded forms.
StringBuilder.Insert(position, string) Inserts the string representation of the specified object at the specified index of this StringBuilder object.
StringBuilder.Replace(char, char)

StringBuilder.Replace(string, string)

Replaces all occurrences of the first supplied character (or string) with the second supplied character (or string) in this StringBuilder object.
StringBuilder.Remove(int i, int length) Remove all characters from the index position i of specified length in the current StringBuilder object.
StringBuilder.Equals(StringBuilder) Checks the supplied StringBuilder object with this instance and returns true if both are identical; otherwise, it returns false.

The following program demonstrates the use of StringBuilder class in C#.

using System;
using System.Text;

namespace StringBuilderDemo
{
    class Program
    {
        public static void Main(string[] args)
        {
            StringBuilder sb = new StringBuilder("This is the StringBuilder class!");
            String str = " Great!!!";
            Console.WriteLine("Length of StringBuilder sb is: " + sb.Length);
            Console.WriteLine("Capacity of StringBuilder sb is: " + sb.Capacity);
            Console.WriteLine("StringBuilder sb after appending: " + sb.Append(str));
            Console.WriteLine("StringBuilder sb after removing: " + sb.Remove(4, 3));

            Console.ReadLine();
        }
    }
}

the output of the above C# program…

StringBuilder-class-demo


C#

Leave a Reply