C# - StringBuilder
A String is immutable, meaning String cannot be changed once created. For example, new string "Hello World!!" will occupy a memory space on the heap. Now, by changing the initial string "Hello World!!" to "Hello World!! from Tutorials Teacher" will create a new string object on the memory heap instead of modifying the initial string at the same memory address. This behaviour will hinder the performance if the same string changes multiple times by replacing, appending, removing or inserting new strings in the initial string.
To solve this problem, C# introduced StringBuilder. StringBuilder is a dynamic object that allows you to expand the number of characters in the string. It doesn't create a new object in the memory but dynamically expands memory to accommodate the modified string.
StringBuilder Initialization
StringBuilder can be initialized the same way as class.
StringBuilder sb = new StringBuilder();
//or
StringBuilder sb = new StringBuilder("Hello World!!");
You can give an initial capacity of characters by passing an int value in the constructor. For example, the following will allocate memory of 50 characters sequentially on the memory heap. The memory allocation automatically expands once it reaches the capacity.
StringBuilder sb = new StringBuilder(50);
//or
StringBuilder sb = new StringBuilder("Hello World!!",50);
Important Methods of StringBuilder
Method Name | Description |
---|---|
StringBuilder.Append(valueToAppend) | Appends the passed values to the end of the current StringBuilder object. |
StringBuilder.AppendFormat() | Replaces a format specifier passed in a string with formatted text. |
StringBuilder.Insert(index, valueToAppend) | Inserts a string at the specified index of the current StringBuilder object. |
StringBuilder.Remove(int startIndex, int length) | Removes the specified number of characters from the given starting position of the current StringBuilder object. |
StringBuilder.Replace(oldValue, newValue) | Replaces characters with new characters. |
Append()/AppendLine()
Use Append method of StringBuilder to add or append a string to StringBuilder. AppendLine() method appends the string with a newline at the end.
StringBuilder sb = new StringBuilder("Hello ",50);
sb.Append("World!!");
sb.AppendLine("Hello C#!");
sb.AppendLine("This is new line.");
Console.WriteLine(sb);
This is new line.
AppendFormat()
Use AppendFormat method to format input string into specified format and then append it.
StringBuilder amountMsg = new StringBuilder("Your total amount is ");
amountMsg.AppendFormat("{0:C} ", 25);
Console.WriteLine(amountMsg);
Insert()
The Insert() method inserts the string at specified index in StringBuilder.
StringBuilder sb = new StringBuilder("Hello World!!",50);
sb.Insert(5," C#");
Console.WriteLine(sb);
Remove()
The Remove() method removes the string at specified index with specified length.
StringBuilder sb = new StringBuilder("Hello World!!",50);
sb.Remove(6, 7);
Console.WriteLine(sb);
Replace()
The Replace() method replaces all occurance of a specified string with a specified replacement string.
StringBuilder sb = new StringBuilder("Hello World!!",50);
sb.Replace("World", "C#");
Console.WriteLine(sb);
Indexer
You can use indexer with StringBuilder to get or set a character at specified index. The following example uses indexer to get all the characters of StringBuilder using for loop.
StringBuilder sb = new StringBuilder("Hello World!!");
for(int i=0; i< sb.Length; i++)
Console.Write(sb[i]);
ToString()
Use ToString() method to get string from StringBuilder.
StringBuilder sb = new StringBuilder("Hello World!!");
string str = sb.ToString(); // "Hello World!!"
- StringBuilder is mutable.
- StringBuilder performs faster than string when appending multiple string values.
- Initialize StringBuilder as class e.g.
StringBuilder sb = new StringBuilder()
- Use StringBuilder when you need to append more than three or four strings.
- Use Append() method to add or append strings with StringBuilder.
- Use ToString() method to get the string from StringBuilder.