Manipulating C# Strings More Efficiently with StringBuilder

C# Programming Guide

In this C# programming tutorial, we will talk about the C# StringBuilder class, its methods, and properties. StringBuilder is a class in C# that you may use to perform repetitive operations on a string.

Interested in learning C# in a classroom or online course environment? We have an article highlighting the Best Online Courses to Learn C# to help you get started.

What is the StringBuilder Class in C#?

A string is immutable in C#, which means it cannot be changed. Once you create a set of characters, they cannot be changed further. If a developer makes changes or updates to a string, it will result in the creation of another object in memory. Because of this, if a programmer performs repetitive operations on the same string, it can cause performance issues for the application.

The StringBuilder class was introduced to solve this problem. It performs dynamic allocation of memory. When any modification is done to a string using a StringBuilder object, it does not allocate new memory for it; instead, it increases its memory size to accommodate new characters. This is how StringBuilder functions.

In the next section, we will look at how to initialize the StringBuilder class, then delve into the Capacity property and different methods provided by StringBuilder to manipulate strings.

Declaring and Initializing StringBuilder in C#

The StringBuilder class is present in the System.Text namespace, so if we require it in our programs, we must import the System.Text namespace. The way we declare and initialize a StringBuilder is similar to that of any class in C#; developers can initialize a StringBuilder class in C# as follows:

StringBuilder sb = new StringBuilder();

or:

StringBuilder sb = new StringBuilder("Hello there!");	

Read: Productivity Tools for .NET Developers

What is the C# StringBuilder Property Capacity?

As we already know, StringBuilder is a dynamic object, which can increase its size to accommodate any number of characters. Programmers can also provide an initial capacity (i.e. number of characters) a StringBuilder object can hold by specifying the Capacity property or an integer value using one of the overloaded constructors.

The following code example shows how to use the Capacity property of a StringBuilder object in C#:

StringBuilder sbObj = new StringBuilder(40);

//or

StringBuilder sbObj = new StringBuilder("This is an example of initializing a StringBuilder object", 100);

//or

sbObj.Capacity = 40;

Whenever appending strings, it is possible that the capacity of the StringBuilder object becomes less than the appended string value; in this case, the capacity of StringBuilder will be adjusted automatically to hold the appended string value. By default, the capacity of StringBuilder is 16 and it is capable of storing up to 12 billion characters.

StringBuilder Methods in C#

StringBuilder provides different methods for manipulating strings, which are listed in the following section.

Append Method

As the name implies, the Append method appends the set of characters at the end of the StringBuilder. The method is really helpful when you want to concatenate several strings to a given string:

class Program
{
    public static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder("This is an example");
        Console.WriteLine(sb);
        sb.Append("of Append Method");
        Console.WriteLine(sb);
        Console.ReadLine();
    }
}

In the above example, we have defined a string using StringBuilder. Then we appended another set of characters to it using the Append() method. The above program will produce the following output:

Before appending a new string:

This is an example

After appending a new string:

This is an example of Append Method

Read: Project Management Software for .NET Developers

Insert Method

The Insert() method is used to insert one or more characters at the specified index. It is used in the condition where some character set needs to be inserted at the specified position in the given string.

Consider the following example, which demonstrates how to use the Insert() method in C#:

StringBuilder sb = new StringBuilder("Hello!");
Console.WriteLine(sb);
sb.Insert(5, "World");
Console.WriteLine(sb);
Console.ReadLine();

This results in the following output:

Hello !
Hello World!

As you can see in the above code, the insert method accepts two parameters. The first parameter is an integer value that specifies the index where characters are to be inserted and the second parameter is the set of characters the user wants to insert at the specified index.

Remove Method

The Remove() method is used to remove a certain set of characters from a given string. It removes characters from a string within a given range. This method is useful in the condition where certain characters need to be removed from the StringBuilder. Consider the following example of how to use Remove() in C#:

StringBuilder sb = new StringBuilder("Larger");
sb.Append("than Life");
sb.WriteLine(sb);
sb.Remove(5, 6);
Console.WriteLine(sb);

This produces the following output:

Larger than Life
Large Life

In the above example, we specified the starting index as 5 and length as 6. So, the StringBuilder object starts removing the characters from index 5 and replaces 6 characters. Thus ‘r than’ will get removed from the StringBuilder object.

Clear Method

The Clear() method removes all the characters from a given set of characters. It is recommended to use it in conditions where a programmer wants to remove all of the characters or needs an empty string:

StringBuilder sb = new StringBuilder("Bailey is in");
Console.WriteLine(sb);
strgBldr.Append("the living room");
Console.WriteLine(strgBldr);
strgBldr.Clear();
Console.WriteLine(strgBldr);
Console.ReadLine();

This results in the following output:

>Bailey is in
>Bailey is in the living room
>

In the above program, we started off by appending a string to a StringBuilder object and then its printed value. After that, we used Clear() to remove all the characters from the StringBuilder object. When we tried to print its value, it resulted in a blank value.

Replace Method

The Replace() method is used to replace all of the occurrences of the specified string with the value provided by the user. The method is useful in scenarios where developers want to replace some character at a specific index with another set of characters. Consider the following example:

StringBuilder str = new StringBuilder("She is an amazing person");
Console.WriteLine(str);
str.Replace("amazing", "interesting");
Console.WriteLine(str);
Console.ReadLine();

The result:

She is an amazing person 
She is an interesting person

In the above program, we used the Replace() method to replace the word ‘amazing’ with ‘interesting’. Replace() accepts two parameters. The first one is the set of characters you want to replace and the second one would be the string the programmers wants to replace it with.

Final Thoughts on C# StringBuilder

In C#, StringBuilder is a class used for enhancing the performance of applications by performing repetitive operations on a string without creating another string object in memory. Unlike a string, StringBuilder is mutable, so whenever you modify a string, it does not create another string object in memory, but, instead, performs the modification on the same object. This helps C# programmers to improve the performance of applications by dynamically increasing the memory size (if required) to accommodate more data at runtime and lightens the burden of resources.

Read more C# programming tutorials and software development guides.

Tariq Siddiqui
Tariq Siddiqui
A graduate in MS Computer Applications and a Web Developer from India with diverse skills across multiple Web development technologies. Enjoys writing about any tech topic, including programming, algorithms and cloud computing. Traveling and playing video games are the hobbies that interest me most.

More by Author

Must Read