How to use StringBuilder in C#
StringBuilder in C# is a mutable string class that efficiently handles string modifications. Unlike regular strings which are immutable, StringBuilder modifies the same object, avoiding memory allocations for each change.
Use StringBuilder when concatenating strings in loops or making many modifications. For simple concatenations, regular string operations or interpolation are more readable and often sufficient.
StringBuilder provides methods like Append(), AppendLine(), Insert(), Remove(), and Replace() for efficient string manipulation.
C# Example Code
using System;
using System.Text;
public class StringBuilderUsage
{
public static void Main(string[] args)
{
// Basic StringBuilder usage
StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append(" ");
sb.Append("World");
Console.WriteLine(sb.ToString()); // Hello World
// AppendLine for new lines
StringBuilder message = new StringBuilder();
message.AppendLine("Line 1");
message.AppendLine("Line 2");
message.AppendLine("Line 3");
Console.WriteLine(message.ToString());
// Method chaining
StringBuilder chain = new StringBuilder()
.Append("First")
.Append(" ")
.Append("Second")
.Append(" ")
.Append("Third");
Console.WriteLine(chain.ToString());
// Building strings in loops (efficient)
StringBuilder loop = new StringBuilder();
for (int i = 1; i <= 5; i++)
{
loop.Append($"Number {i}, ");
}
Console.WriteLine(loop.ToString().TrimEnd(',', ' '));
// Insert and Remove
StringBuilder edit = new StringBuilder("Hello World");
edit.Insert(6, "Beautiful "); // Insert at position
Console.WriteLine(edit); // Hello Beautiful World
edit.Remove(6, 10); // Remove 10 chars from position 6
Console.WriteLine(edit); // Hello World
// Replace
StringBuilder replace = new StringBuilder("The cat and the cat");
replace.Replace("cat", "dog");
Console.WriteLine(replace); // The dog and the dog
// Initial capacity for performance
StringBuilder capacity = new StringBuilder(1000); // Pre-allocate space
for (int i = 0; i < 100; i++)
{
capacity.Append($"Item {i}, ");
}
Console.WriteLine($"Built {capacity.Length} characters");
}
}