In C#, the string type is immutable. It means a string cannot be changed once created. For example, a new string, “Hello World!” will occupy a memory space on the heap. Now, by changing the initial string “Hello World!” to “Hello World! from InterviewBit” will create a new string object on the memory heap instead of modifying an original string at the same memory address. This behavior would hinder the performance if the original string changed multiple times by replacing, appending, removing, or inserting new strings in the original string.
To solve this problem, C# introduced the StringBuilder
in the System.Text
namespace. The StringBuilder
doesn’t create a new object in the memory but dynamically expands memory to accommodate the modified string.
You can create an object of the StringBuilder
class using the new
keyword and passing an initial string. The following example demonstrates creating StringBuilder objects.
using System.Text; // include at the top
StringBuilder sb = new StringBuilder(); //string will be appended later
//or
StringBuilder sb = new StringBuilder("Hello World!");
Optionally, you can also specify the maximum capacity of the StringBuilder object using overloaded constructors.
The StringBuilder
is not the String
. Use the ToString()
method to retrieve a string from the StringBuilder
object.
StringBuilder sb = new StringBuilder("Hello World!");
String greet = sb.ToString(); //returns "Hello World!"
Use the Append()
method to append a string at the end of the current StringBuilder object. If a StringBuilder does not contain any string yet, it will add it. The AppendLine()
method append a string with the newline character at the end.
StringBuilder sb = new StringBuilder();
sb.Append("Hello ");
sb.AppendLine("World!");
sb.AppendLine("Hello C#");
Console.WriteLine(sb);
Output:
Hello World!
Hello C#.
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.In the editor below, perform the different tasks as directed.