StringBuilder
Struct · namespace System
struct StringBuilderBuilds a string without copying it for every ‘+’.
using System;
var sb = StringBuilder.Create();sb.Append("x = ");sb.Append(42.ToString());sb.Append('\n');string text = sb.ToString();Like List<T>, a StringBuilder is a small handle to shared storage: copies see the same text. The storage is made
by StringBuilder.Create(); the zero value (new(), a field without a value) is an empty text that can be read but
not changed: Append panics.
Static methods
Section titled “Static methods”| Name | Description |
|---|---|
Create |
A new, empty builder. |
Create
Section titled “Create”static StringBuilder Create()A new, empty builder.
static StringBuilder Create(int capacity)A new, empty builder with room for capacity bytes before it has to grow.
Methods
Section titled “Methods”| Name | Description |
|---|---|
IsCreated |
Whether the builder has storage: made by Create(), not the zero value (which cannot change). |
Length |
The length of the text so far, in bytes. |
Append |
Appends text: a string or a part of one (a StringSlice; a string converts to it for free). |
AppendLine |
Appends text and a line break (\n). |
Get |
The character (byte) at index; the text is UTF-8. |
Clear |
Removes all text. |
Substring |
The text from start to the end, as a new string. |
Truncate |
Cuts the text to its first length bytes. |
ToString |
The text as a string. |
IsCreated
Section titled “IsCreated”bool IsCreated()Whether the builder has storage: made by Create(), not the zero value (which cannot change).
Since 0.26
Length
Section titled “Length”int Length()The length of the text so far, in bytes.
Append
Section titled “Append”void Append(StringSlice text)Appends text: a string or a part of one (a StringSlice; a string converts to it for free).
Panics when the builder was not created (StringBuilder.IsCreated).
void Append(char c)Appends the character c (a byte).
AppendLine
Section titled “AppendLine”void AppendLine(StringSlice text)Appends text and a line break (\n).
void AppendLine()Appends a line break (\n).
char Get(int index)The character (byte) at index; the text is UTF-8.
Panics when index is not in 0 to Length() - 1.
void Clear()Removes all text.
Substring
Section titled “Substring”string Substring(int start)The text from start to the end, as a new string.
Panics when start is not in 0 to Length().
Truncate
Section titled “Truncate”void Truncate(int length)Cuts the text to its first length bytes.
Panics when length is not in 0 to Length().
ToString
Section titled “ToString”string ToString()The text as a string.