What is the purpose of the StringBuilder class in C#?


In C#, strings are immutable. That means you cannot modify a string once it's created. Any modification to the string returns a new string that contains the modification, leaving the original string intact.

string word = "aaabbbccc";
string newWord = word.Replace('b', 'd');
Console.WriteLine(word); // prints aaabbbccc
Console.WriteLine(newWord); // prints aaadddccc

StringBuilder class represents a string-like object that can be modified, i.e. a mutable string of characters. It's implemented differently than the string type, which represents an immutable string of characters.

As modifying a string object creates a copy, repeatedly modifying string objects can incur a performance penalty. For small repetitions it's negligible, but can be significant for huge loops. StringBuilder provides an efficient alternative to modify a string by appending, removing, replacing, or inserting characters.

StringBuilder maintains an internal buffer to hold the characters. If there is space available in the buffer, it appends new data. Otherwise, it creates a new buffer, copies the old data to the new buffer, and then appends the data.

var sb = new StringBuilder();
for (int i = 0; i < 10; i++){
   sb.Append("a");
}
Console.WriteLine(sb.ToString()); // prints aaaaaaaaaa

Here are the different ways to construct a StringBuilder object.

// Initialize a new instance of StringBuilder
var sb1 = new StringBuilder();

// Initialize a new instance of StringBuilder using the given capacity
var sb2 = new StringBuilder(capacity: 10);

// Initialize a new instance of StringBuilder with the given string
var sb3 = new StringBuilder(value: "Hello World");

// Initialize a new instance of StringBuilder with the given capacity and the maximum capacity it can grow to
var sb4 = new StringBuilder(capacity: 20, maxCapacity: 10);

// Initialize a new instance of StringBuilder with the given string and capacity
var sb5 = new StringBuilder(value: "Hello", capacity: 20);

// Initialize a new instance of StringBuilder from the given substring and capacity
var sb6 = new StringBuilder(value: "Hello World", startIndex: 0, length: 5, capacity: 20);

StringBuilder class has a Length property indicating the number of characters the object currently has. Upon adding more characters to the object, its length increases until it reaches its capacity, which defines the maximum number of characters that the object can currently contain.

If the number of added characters causes the length to exceed its current capacity, the class allocates new memory, coupling its capacity. Then the new characters are added to the object, and its Length property is adjusted.

StringBuilder keeps adding additional memory dynamically until it reaches the value of the MaxCapacity property. After that, no further memory can be allocated for the object. If you try to add more data to the object, it throws either an ArgumentOutOfRangeException or an OutOfMemoryException exception.

StringBuilder provides the following methods that make it easy to modify the strings.

  • Append − Appends the string representation of a specified object to this instance.

  • AppendFormat − Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. Each format item is replaced by the string representation of a corresponding object argument.

  • AppendJoin − Concatenates the string representations of the elements in the provided array of objects, using the specified separator between each member, then appends the result to the current instance of the string builder.

  • AppendLine − Appends the default line terminator to the end of the current StringBuilder object.

  • Clear − Removes all the characters from the current StringBuilder instance.

  • CopyTo − Copies the characters to a destination char span or char array.

  • EnsureCapacity − Ensures that the capacity of this instance of StringBuilder is at least the specified value.

  • Equals − Returns true if this instance and the provided instance have equal string, Capacity, and MaxCapacity values.

  • GetChunks − Returns an object that can be used to iterate through the chunks of characters.

  • Insert − Inserts the string representation of a specified object into this instance at a specified character position.

  • Remove − Removes the specified range of characters from this instance.

  • Replace − Replaces all occurrences of a specified character or string in this instance with another specified character or string.

  • ToString − Converts the current instance to a string.

Example

 Live Demo

using System;
using System.Text;
class Program{
   static void Main(string[] args){
      string word = "aaabbbccc";
      string newWord = word.Replace('b', 'd');
      Console.WriteLine(word); // prints aaabbbccc
      Console.WriteLine(newWord); // prints aaadddccc
      var sb = new StringBuilder();
      for (int i = 0; i < 10; i++){
         sb.Append("a");
      }
      Console.WriteLine(sb.ToString()); // prints aaaaaaaaaa

      // Initialize a new instance of StringBuilder
      var sb1 = new StringBuilder();

      // Initialize a new instance of StringBuilder using the given capacity
      var sb2 = new StringBuilder(capacity: 10);
     
      // Initialize a new instance of StringBuilder with the given string
      var sb3 = new StringBuilder(value: "Hello World");
      // Initialize a new instance of StringBuilder with the given capacity and the    maximum capacity it can grow to
      var sb4 = new StringBuilder(capacity: 20, maxCapacity: 50);
      // Initialize a new instance of StringBuilder with the given string and capacity
      var sb5 = new StringBuilder(value: "Hello", capacity: 20);

      // Initialize a new instance of StringBuilder from the given substring and capacity
      var sb6 = new StringBuilder(value: "Hello World", startIndex: 0, length: 5, capacity: 20);
   }
}

Output

aaabbbccc
aaadddccc
aaaaaaaaaa

Updated on: 19-May-2021

355 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements