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

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...

ASP.NET MVC Views

Views in ASP.NET MVC Application explained Find a related article By  Steve Smith  and  Luke Latham from Microsoft Corporation here In the Model-View-Controller (MVC) pattern, the  view  handles the application's data presentation and user interaction. A view is an HTML template with embedded  Razor markup . Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET MVC, views are  .cshtml  files that use the  C# programming language  in Razor markup. Usually, view files are grouped into folders named for each of the application's  controllers . The folders are stored in a  Views  folder at the root of the application as shown: The  Home  controller is represented by a  Home  folder inside the  Views  folder.  The  Home  folder contains the views for the  About ,  Contact , and  Index...

ASP.NET MVC Routing

ASP.NET MVC Routing ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Routing pattern is as follows A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser. Route Properties ASP.NET MVC routes are res...