Learn To Use C# StringBuilder Class And Its Methods With Examples

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 7, 2024

This Tutorial Explains The C# StringBuilder Class And Its Methods Like Append, Clear, Remove, Insert, Replace, and Equals in Detail with Examples:

StringBuilder class in C# works with the string when the use of repetitive string operations are required.

A string is immutable i.e. it cannot be changed. Once a certain string is created, it cannot be changed. Any change or update to the String will create a new string object in the memory. As it is evident, this behavior will hamper the performance if the recurring operation is performed on the same string.

=> Check Out The In-Depth C# Training Tutorials Here

StringBuilder class in C#

StringBuilder class in C# aims to solve this problem. It allows dynamic allocation of memory i.e. it can expand the number of characters in the string. It doesn’t create a new memory object rather it dynamically increases the memory size to contain new characters.

How To Initialize C# StringBuilder?

StringBuilder is initialized similarly to any other class. The StringBuilder class is present in the System namespace. The text needs to be imported in the class for instantiation.

Example for Initialization:

    
class Program
       {
             public static void Main(string[] args)
              {
    
                     StringBuilder strgBldr = new StringBuilder("Hello");
                     Console.WriteLine(strgBldr);
                     Console.ReadLine();
                }
        }

The output of the above program is:

Hello

C# StringBuilder Methods

StringBuilder class also offers several different methods to work on string manipulation.

#1) Append Method

As suggested by the name it appends a set of characters or string at the end of the current String Builder. It is very helpful in improving performance when several string concatenations are required to be performed on the same string.

Example:

class Program
       {
             public static void Main(string[] args)
               {
                   StringBuilder strgBldr = new StringBuilder("Hello");
                   Console.WriteLine(strgBldr);
                   strgBldr.Append("World");
                   Console.WriteLine(strgBldr);
                   Console.ReadLine();
                 }
         }

The output of the above program will be:

Hello
Hello World

In the above program, we first had a string defined via stringBuilder. Then we used the Append() to concatenate another string with the previous one. If we execute the code line before append then it has the output as “Hello” but once we append it and print the result it will print “Hello World” i.e. the previous string with the appended string.

#2) Clear Method

This method removes all the characters from the current StringBuilder. It is very helpful in scenarios where we need to get an empty string or where we need to clear the data from a string variable.

Example:

class Program
       {
             public static void Main(string[] args)
              {
                    StringBuilder strgBldr = new StringBuilder("Hello");
                    Console.WriteLine(strgBldr);
                    strgBldr.Append("World");
                    Console.WriteLine(strgBldr);
                    strgBldr.Clear();
                    Console.WriteLine(strgBldr);
                    Console.ReadLine();
                }
        }

The output of the above program is:

Hello
Hello World

When we perform a clear operation on StringBuilder and then try to print the resultant string. We will get a black string value. In the above program, we have appended the value into StringBuilder and we printed the value to console.

Then we performed a clear operation that removed all the value from StringBuilder after that when we tried to print, it printed a blank value.

#3) Remove Method

Remove is similar to clear but with a little difference. It also removes the characters from the StringBuilder but it does so within a given range unlike clear which removes all the characters present in the StringBuilder. Remove is used whenever the scenario requires the program to remove a certain set of characters from the String instead of the whole string.

Example:

class Program
       {
                public static void Main(string[] args)
                {
                        StringBuilder strgBldr = new StringBuilder("Hello");
                        Console.WriteLine(strgBldr);
                        strgBldr.Append("World");
                        Console.WriteLine(strgBldr);
                        strgBldr.Remove(2, 3);
                        Console.WriteLine(strgBldr);
                        Console.ReadLine();
                 }
        }

The output of the above program will be:

Hello
Hello World
He World

Remove accepts two parameters, the first one signifies the starting index i.e. index of the character from where you want to start removing. The second parameter also accepts integer which signifies length i.e. the length of the character from which you want to remove.

In the above program, we provided the starting index as 2 and length as three. So, it started removing the character from index 2 i.e. He’l’lo and we gave the length as three so, the program removed three characters from ‘l’ thus ‘l l o’ was removed.

#4) Insert Method

It inserts one or more characters inside the string at the given index. It also allows the user to specify the number of times the string or character has to be inserted into the StringBuilder. It is used in the conditions where the characters are required to be inserted into the given string at a specific position.

Example:

class Program
       {
              publicstaticvoid Main(string[] args)
              {
                     StringBuilder strgBldr = new StringBuilder("Hello World");
                    Console.WriteLine(strgBldr);
                    strgBldr.Insert(2, "_insert_");
                    Console.WriteLine(strgBldr);
                    Console.ReadLine();
                }
        }

The output of the above program will be:

Hello World
He_insert_llo World

In the above program, the Insert method is used to insert characters at a certain index. The insert method accepts two parameters. The first parameter is an integer which signifies the index where the characters are to be inserted. The second parameter accepts characters that the user wants to insert at the given index.

#5) Replace Method

The replace method replaces all the occurrences of the specified string in the StringBuilder by the string or character provided by the user. It replaces specific characters at a specific index. It can be used in scenarios where some of the characters are required to be replaced by another character.

Example:

class Program
       {
               public static void Main(string[] args)
               {
                      StringBuilder strgBldr = new StringBuilder("Hello World");
                      Console.WriteLine(strgBldr);
                      strgBldr.Replace("Hello", "Hi");
                      Console.WriteLine(strgBldr);
                      Console.ReadLine();
                 }
        }

The output of the above program is:

Hello World
Hi World

In the above program, we used the Replace method to replace “Hello” with “Hi”. The replace method accepts two parameters, the first one is the string or characters that you want to replace and the second one is the string or character you want to replace it with.

#6) Equals Method

As the name suggests it validates if one StringBuilder is equal to others or not. It accepts StringBuilder as a parameter and returns a Boolean value based on the equality condition achieved. This method is quite useful if you want to validate the equality condition for two StringBuilders.

Example:

class Program
       {
               public static void Main(string[] args)
                {
                         StringBuilder strgBldr1 = new StringBuilder("Hello World");
                         StringBuilder strgBldr2 = new StringBuilder("World");
                         StringBuilder strgBldr3 = new StringBuilder("Hello World");
           
                        Console.WriteLine(strgBldr1.Equals(strgBldr2));
                        Console.WriteLine(strgBldr1.Equals(strgBldr3));
            
                        Console.ReadLine();
                }
         }

The output of the above program will be:

False
True

In the above program, the first and the third StringBuilder objects are equal i.e. they have the same value. Hence, when we equated first with the second, it returned a false value but when we equated first and third being equal it returned true.

Conclusion

StringBuilder class in C# is used for improving performance where multiple operations on a string are performed.

Being immutable, whenever a string is modified it creates another string object in the memory. The StringBuilder aims to reduce that.

It allows the user to perform modification on the same object by allocating dynamic memory. This means that it can increase the memory size if required to accommodate more data.

=> Read Through The C# Guide For Beginners Here

Was this helpful?

Thanks for your feedback!

Leave a Comment