Most of the programmer use string, as they are easy to use and provides effective interaction with the user. Every time we manipulate a string object we get a new string object created.
String is immutable means that once it has been created, a string cannot be changed. No characters can be added or removed from it, nor can its length be changed.
The String object is immutable while StringBuilder object is mutable. Both String and StringBuilder are reference type. But String acts like a value type.
StringBuilder is located in the System.Text namespace.
The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. Using the StringBuilder class can boost performance when concatenating many strings together in a loop.
The following table lists the methods you can use to modify the contents of a StringBuilder.
Method |
Description |
StringBuilder.Append |
Appends information to the end of the current StringBuilder. |
StringBuilder.AppendFormat |
Replaces a format specifier passed in a string with formatted text. |
StringBuilder.Insert |
Inserts a string or object into the specified index of the current StringBuilder. |
StringBuilder.Remove |
Removes a specified number of characters from the current StringBuilder. |
StringBuilder.Replace |
Replaces a specified character at a specified index. |
Program to explain StringBuilder Class
using System;
using System.Text;
namespace StringBuilder_example
{
class Program
{
static void Main(string[] args)
{
StringBuilder sbstr = new StringBuilder("We are the world");
Console.WriteLine(sbstr);
sbstr.Append(" we are the people");
Console.WriteLine(sbstr);
float currency=3400.50f;
sbstr.AppendFormat(" Our individual salary : {0:C}. ", currency);
Console.WriteLine(sbstr);
sbstr.Insert(11, "people of ");
Console.WriteLine(sbstr);
sbstr.Remove(11, 10);
Console.WriteLine(sbstr);
sbstr.Replace("world", "Indian");
Console.WriteLine(sbstr);
Console.ReadKey();
}
}
}
Output of above program
Difference between String and StringBuilder class
String |
StringBuilder |
System.String is immutable |
System.StringBuilder is mutable |
Concatenation is used to combine two strings |
Append method is used. |
The first string is combined to the other string by creating a new copy in the memory as a string object, and then the old string is deleted |
Insertion is done on the existing string. |
String is efficient for small string manipulation |
StringBuilder is more efficient in case large amounts of string manipulations have to be performed |
Conclusion
I hope that this article would have helped you in understanding StringBuilder Class in C#. StringBuilder can improve the performance of your application.
Your feedback and constructive contributions are welcome. Please feel free to contact me for feedback or comments you may have about this article.