Skip to main content

StringBuilder in C# with Example

StringBuilder in C# with Example

StringBuilder is a class that is useful to represent a mutable string of characters and it is an object of System.Text namespace.

 

Like string we can use a StringBuilder to create variables to hold any kind of text which is a sequential collection of characters.

 

In C#, both string and StringBuilder will represent a sequence of characters and perform the same kind of operations but the only difference is strings are immutable and StringBuilder is mutable.

 

Generally, the string object cannot be modified once it created. If any changes made to the string object like add or modify an existing value, then it will simply discard the old instance in memory and create a new instance to hold the new value. In case, if we are doing repeated modifications on the string object, then it will affect the performance of application.

 

To solve this problem, C# introduced an alternative called StringBuilder, which is a mutable string class. Mutability means once an instance of the class is created, then the same instance will be used to perform any operations like inserting, appending, removing or replacing the characters instead of creating a new instance for every time.

 

The StringBuilder is a dynamic object which will expand a memory dynamically to accommodate the modifications of string instead of creating a new instance in the memory.

 

StringBuilder Declaration and Initialization

As discussed, the StringBuilder class is an object of System.Text namespace so to use StringBuilder in our application, we need to import the System.Text namespace.

 

The StringBuilder declaration and initialization will be the same as class. The following are the different ways of declaring and initializing a stringbuilder in C#.

 

StringBuilder sb = new StringBuilder();

//or

StringBuilder sb = new StringBuilder("Welcome to CsharpnaijaTutorial");

 

From the above code snippet, we created an instance of the StringBuilder class by defining our variable with overloaded constructor methods.

 

StringBuilder Capacity

As discussed, the StringBuilder is a dynamic object which will expand dynamically to accommodate the number of characters based on the string modifications. We can also specify an initial capacity of characters the StringBuilder can hold by passing an int value using one of the overloaded constructors or by using StringBuilder Capacity property.

 

For example, we created a StringBuilder by specifying the capacity of 50 characters and appending a string whose length is greater than the capacity of 50 characters. In this case, the new space will be allocated automatically and the capacity of StringBuilder will be doubled.

 

The following code snippets shows example of specifying the initial capacity of characters the StringBuilder can hold in c# programming language.

 

StringBuilder stringBuilder = new StringBuilder(50);

//or

StringBuilder stringBuilder = new StringBuilder("Welcome to Csharpnaija", 50);

//or

stringBuilder.Capacity = 50;

 

 

Whenever the defined capacity of StringBuilder is lesser than the appended string value, then the current capacity of StringBuilder automatically will increase to match the appended string value.

 

The default capacity of StringBuilder is 16 characters and its maximum capacity is more than 12 billion characters.

 

StringBuilder Methods

The following table lists the important methods of StringBuilder which we can use to modify the contents of StringBuilder.

 

Method

Description

StringBuilder.Append

This method will append the given string value to the end of the current StringBuilder.

StringBuilder.AppendFormat

It will replace a format specifier passed in a string with formatted text.

StringBuilder.Insert

It inserts a string at the specified index of current StringBuilder.

StringBuilder.Remove

It removes a specified number of characters from the current StringBuilder.

StringBuilder.Replace

It replaces a specified character at a specified index.

 

StringBuilder.Append Method

The Append method is used to add or append a string objects at the end of the string represented by the StringBuilder.

The following code block show example of initializing a StringBuilder with some text and appending a required text at the end of the string object.

StringBuilder stringBuilder = new StringBuilder("Musa");

stringBuilder.Append(", Gadabs");

stringBuilder.Append(", Sule");

Console.WriteLine(stringBuilder);

 // Output: Musa, Gadabs, Sule


StringBuilder.AppendFormat Method

The AppendFormat method is used to add or append a string objects by formatting into specified format at the end of string represented by the StringBuilder.

 

Following is the example of initializing a StringBuilder with some text and appending a formatted text at the end of the string object.

 

int amount = 1506;

StringBuilder stringBuilder = new StringBuilder("Total");

stringBuilder.AppendFormat($": {amount:c}");

Console.WriteLine(stringBuilder.ToString());

// Output is Total: ?1,506.00

 

StringBuilder.Insert Method

The Insert method is used to insert a string at the specified index position of current StringBuilder object.

 

The code below shows example of initializing a StringBuilder with some text and inserting a string at the specified index position of StringBuilder object.

 

StringBuilder stringBuilder = new StringBuilder("Welcome Csharpnaija");

stringBuilder.Insert(8, "to ");

Console.WriteLine(stringBuilder);

 

// Output: Welcome to Csharpnaija

 

StringBuilder.Remove Method

The Remove method is used to remove a specified number of characters from the current StringBuilder object, starting from the specified index position.

 

The following is the example of removing a specified number of characters from the StringBuilder object, starting from the specified index position.

 

StringBuilder stringBuilder = new StringBuilder("Welcome to Csharpnaija");

stringBuilder.Remove(8, 3);

Console.WriteLine(stringBuilder);

 // Output: Welcome Csharpnaija


StringBuilder.Replace Method

The Replace method is used to replace all occurrences of specified string characters in current StringBuilder object with a specified replacement string characters.

 

Below is the example of replacing a specified number of characters from the StringBuilder object, with specified replace characters.

 

StringBuilder stringBuilder = new StringBuilder("Welcome to Csharpnaija");

stringBuilder.Replace("Csharpnaija", "C#");

Console.WriteLine(stringBuilder);

 

// Output: Welcome to C#

 

The StringBuilder has another method called AppendLine() which is used to add a newline at the end of string.

 

Convert StringBuilder to String

A StringBuilder object can be converted to a string by calling StringBuilder.ToString() method.

 

The example below shows how to convert a StringBuilder object to a string using the ToString() method in C#.

 

using System;

using System.Text;

namespace CsharpnaijaTutorial

{

    class Program

    {

        static void Main(string[] args)

        {

            StringBuilder stringBuilder = new StringBuilder("Musa");

            stringBuilder.Append(", Sule");

            stringBuilder.Append(", Gadabs");

            stringBuilder.AppendLine();

            stringBuilder.Append("Welcome to Csharpnaija");

            Console.WriteLine(stringBuilder.ToString());

            Console.ReadLine();

        }

    }

}

When you execute the above program, you will get the result as shown below.

 Uses of StringBuilder in C#

The following are the important points which we need to remember while using a StringBuilder in C#.

 

  • We need to consider using StringBuilder only when we are unknown about the number of changes that will make to a string at design time otherwise StringBuilder will offer a negligible or no performance improvement over a string.
  • When we are performing a fixed number of concatenation operations on a string, then it’s better to avoid using StringBuilder because it will offer negligible performance.
  • In another case when we expect our application will make a significant number of changes to a string, then we need to use StringBuilder instead of a string.

Thank you

References

1.     Tutlane

2.     TutorialsTeacher

3.     MicrosoftDocumentation


Comments

Popular posts from this blog

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

Most Popular Programming Languages in 2020

Most Popular Programming Languages in 2020 In this blog post, you will learn about the most popular programming languages in 2020 for creating the best web applications. Check its pros and cons. Analyzed by technostacks Not very long ago, just a few people were considered to be computer programmers, and the general public viewed them with awe. In this digital age that we are now living in, however, a large number of IT jobs need a solid grasp of one or more programming languages. Whether one wants to develop a mobile app or get a certification for having programming knowledge, or even to learn new skills, one needs to opt for the right programming language. Below mentioned eight most popular programming languages which are in demand for software development and web applications. This is the most used programming languages in 2019 and will be in 2020. For each, there is little information about the language, benefits and its complexity, as well as about its usage. One must...

HashTable in C# with Example

  HashTable in C# with Example Hashtable  is used to store a collection of key/value pairs of different  data types  and are organized based on the hash code of the key.   Generally, the hashtable object will contain buckets to store elements of the collection. The bucket here, is a virtual subgroup of elements within the hashtable and each bucket is associated with a hash code, which is generated based on the key of an element.   In C#, hashtable is same as a  dictionary  object but the only difference is that the  dictionary  object is used to store a key-value pair of same  data type  elements.   When compared with  dictionary  object, the hashtable will provide a lower performance because the hashtable elements are of object type so the boxing and unboxing process will occur when we are storing or retrieving values from the hashtable.   C# HashTable Declaration Hashtable is a non-generic type...