System.Text.StringBuilder
Overview
The StringBuilder
class represents a mutable string of characters. It provides
methods for efficiently manipulating strings without creating new immutable string
instances.
using System.Text;
var sb = new StringBuilder();
sb.Append("Hello, ");
sb.AppendLine("World!");
Console.WriteLine(sb.ToString());
var sb = new StringBuilder();
sb.Append("Hello, ");
sb.AppendLine("World!");
Console.WriteLine(sb.ToString());
Constructors
StringBuilder()
– Initializes a new instance of theStringBuilder
class.StringBuilder(string value)
– Initializes with the specified string.StringBuilder(int capacity)
– Initializes with a specified capacity.StringBuilder(string value, int capacity)
– Initializes with a string and capacity.
Properties
Property | Type | Description |
---|---|---|
Capacity | int | Gets or sets the current capacity. |
Length | int | Gets or sets the number of characters. |
MaxCapacity | int | Gets the maximum capacity. |
Chars[int index] | char | Gets or sets the character at the specified position. |
Methods
Appends the string representation of an object to the end of the current instance.
public StringBuilder Append(object? value)
Inserts a string at the specified index.
public StringBuilder Insert(int index, string value)
Replaces all occurrences of a specified string with another string.
public StringBuilder Replace(string oldValue, string newValue)
Converts the value of this instance to a String
.
public override string ToString()
Operators
StringBuilder
does not overload any special operators.
Examples
Building a CSV line dynamically:
var sb = new StringBuilder();
string[] columns = { "Id", "Name", "Email" };
foreach (var col in columns)
{
sb.Append(col).Append(',');
}
sb.Length--; // Remove trailing comma
Console.WriteLine(sb.ToString()); // Output: Id,Name,Email
string[] columns = { "Id", "Name", "Email" };
foreach (var col in columns)
{
sb.Append(col).Append(',');
}
sb.Length--; // Remove trailing comma
Console.WriteLine(sb.ToString()); // Output: Id,Name,Email