Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the purpose of the StringBuilder class in C#?
In C#, strings are immutable, meaning you cannot modify a string once it's created. Any modification returns a new string containing the changes, leaving the original intact. The StringBuilder class provides a mutable alternative for efficient string manipulation when you need to perform multiple modifications.
String Immutability Example
using System;
class Program {
static void Main(string[] args) {
string word = "aaabbbccc";
string newWord = word.Replace('b', 'd');
Console.WriteLine(word); // Original unchanged
Console.WriteLine(newWord); // New string with modification
}
}
The output of the above code is −
aaabbbccc aaadddccc
Purpose of StringBuilder
The StringBuilder class represents a mutable string of characters. Unlike regular strings, StringBuilder can be modified in-place without creating new objects. It maintains an internal buffer to hold characters, making it highly efficient for operations like concatenation, insertion, and replacement.
StringBuilder Constructors
The StringBuilder class provides multiple constructors to initialize instances with different configurations −
using System;
using System.Text;
class Program {
static void Main(string[] args) {
// Initialize a new instance of StringBuilder
var sb1 = new StringBuilder();
// Initialize with specified capacity
var sb2 = new StringBuilder(capacity: 10);
// Initialize with initial string
var sb3 = new StringBuilder(value: "Hello World");
// Initialize with capacity and maximum capacity
var sb4 = new StringBuilder(capacity: 20, maxCapacity: 50);
// Initialize with string and capacity
var sb5 = new StringBuilder(value: "Hello", capacity: 20);
// Initialize from substring with capacity
var sb6 = new StringBuilder(value: "Hello World", startIndex: 0, length: 5, capacity: 20);
Console.WriteLine("sb3: " + sb3.ToString());
Console.WriteLine("sb6: " + sb6.ToString());
}
}
The output of the above code is −
sb3: Hello World sb6: Hello
Key Properties
Length − Number of characters currently in the StringBuilder
Capacity − Maximum number of characters the current buffer can hold
MaxCapacity − Maximum capacity the StringBuilder can grow to
Using StringBuilder for Efficient String Building
using System;
using System.Text;
class Program {
static void Main(string[] args) {
var sb = new StringBuilder();
// Append characters efficiently
for (int i = 0; i < 10; i++) {
sb.Append("a");
}
Console.WriteLine("Result: " + sb.ToString());
// Demonstrate various StringBuilder methods
sb.Clear();
sb.Append("Hello");
sb.AppendLine(" World");
sb.Append("This is ");
sb.Insert(8, "a test. ");
sb.Replace("Hello", "Hi");
Console.WriteLine("Final result:");
Console.WriteLine(sb.ToString());
Console.WriteLine("Length: " + sb.Length);
Console.WriteLine("Capacity: " + sb.Capacity);
}
}
The output of the above code is −
Result: aaaaaaaaaa Final result: Hi a test. World This is Length: 25 Capacity: 32
Common StringBuilder Methods
| Method | Description |
|---|---|
| Append() | Adds text to the end of the StringBuilder |
| Insert() | Inserts text at specified position |
| Remove() | Removes characters from specified range |
| Replace() | Replaces occurrences of character or string |
| Clear() | Removes all characters |
| ToString() | Converts StringBuilder to string |
Performance Comparison
using System;
using System.Text;
class Program {
static void Main(string[] args) {
// Inefficient string concatenation
string result1 = "";
for (int i = 0; i < 5; i++) {
result1 += "Item" + i + " "; // Creates new string each time
}
Console.WriteLine("String concatenation: " + result1);
// Efficient StringBuilder approach
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
sb.Append("Item").Append(i).Append(" "); // Modifies same buffer
}
Console.WriteLine("StringBuilder result: " + sb.ToString());
}
}
The output of the above code is −
String concatenation: Item0 Item1 Item2 Item3 Item4 StringBuilder result: Item0 Item1 Item2 Item3 Item4
Conclusion
The StringBuilder class is essential for efficient string manipulation in C#. It provides a mutable alternative to immutable strings, using an internal buffer that grows as needed. Use StringBuilder when performing multiple string operations, especially in loops, to avoid the performance penalty of creating multiple string objects.
