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);
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);
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
Comments
Post a Comment