StringBuilder Class Methods


In my previous article we discuss about string class methods and fields. In this article we discuss about StringBuilder class methods. StringBuilder class derives from System.Text namespace.

              StringBuilder sb = new StringBuilder("This is StringBuilder class"", 500);


Capacity() - Retrieves or assigns the number of characters the StringBuilder is capable of holding.

E.g:

                StringBuilder sb = new StringBuilder("This is StringBuilder class", 500);

 

As shown above StringBuilder object sb can hold maximum of 500 characters.

 

Chars() – Set or Get the character at specified character position.

 

Length() - Retrieves or assigns the length of the StringBuilder.

E.g:

                int i = sb.Length;

 

MaxCapacity() - Retrieves the maximum capacity of the StringBuilder.

E.g:

                int i = sb.MaxCapacity;

 

Append() - Overloaded public method that appends a typed object to the end of the current StringBuilder.

E.g:

                sb.Append(" Append method Example");

 

AppendFormat() - Overloaded public method that replaces format specifiers with the formatted

value of an object.

E.g:

                sb.AppendFormat("- {0}", "AppendFormat Example");

 

EnsureCapacity() - Ensures the current StringBuilder has a capacity at least as large as the

specified value.

E.g:

                sb.EnsureCapacity(1000);

 

Insert() - Overloaded public method that inserts an object at the specified position.

E.g:

                sb.Insert(2, " - Insert method");

 

Above code inserts the given text after two characters in StringBuilder sb.

 

Remove() - Removes the specified characters.

E.g:

                sb.Remove(1, 4);

 

Above code removes the string start from first character with the length of four characters in StringBuilder sb.

 

Replace() - Overloaded public method that replaces all instances of specified characters with new characters.

E.g:

                sb.Replace("This", "the");

Above code replaces the string “This” with the string “the” in StringBuilder sb.