StringBuilder Class
Represents a mutable sequence of characters. This class cannot be inherited. It is designed for scenarios where you need to perform many append or insert operations on a string. StringBuilder provides performance advantages over String concatenation because it avoids the creation of multiple intermediate String objects.
The StringBuilder class is part of the System.Text namespace and is used to build strings efficiently.
Unlike immutable String objects, StringBuilder objects can be modified by appending, inserting, deleting, or replacing characters.
This makes it significantly more performant for operations that involve frequent string manipulation.
Capacity
StringBuilder object, which is the sum of the current number of characters plus the remaining space available for allocation before the object's length is increased.
HasChanges
StringBuilder instance has been modified since its creation.
Length
StringBuilder object.
StringBuilder()
StringBuilder class. The default capacity is 16 characters.
StringBuilder(int capacity)
StringBuilder class with a specified initial capacity.
StringBuilder(int capacity, int maxCapacity)
StringBuilder class with a specified initial capacity and maximum capacity.
Append(string value)
- value: The string to append.
Append(char value)
Insert(int index, string value)
- index: The zero-based index at which to insert.
- value: The string to insert.
Remove(int startIndex, int length)
- startIndex: The position within this instance where the removal begins.
- length: The number of characters to remove.
ToString()
The following C# code example demonstrates how to use the StringBuilder class:
using System;
using System.Text;
public class Example
{
public static void Main(string[] args)
{
// Initialize a StringBuilder
StringBuilder sb = new StringBuilder("Hello");
// Append more text
sb.Append(" ");
sb.Append("world!");
// Insert text at a specific position
sb.Insert(5, " beautiful");
// Remove some characters
sb.Remove(0, 6); // Removes "Hello "
// Convert to string and print
Console.WriteLine(sb.ToString());
// Output: beautiful world!
}
}
When you create a StringBuilder object, you can specify its initial capacity.
If the number of characters appended exceeds the capacity, the internal buffer is reallocated to accommodate the new characters.
The Capacity property can be used to retrieve or set the current capacity.
The Length property indicates the number of characters currently in the StringBuilder.
Setting the Length to a value less than the current length truncates the string.
Setting it to a value greater than the current length pads the string with null characters.