Skip to content
CShift0.32

StringBuilder

Struct · namespace System

struct StringBuilder

Builds 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.

Name Description
Create A new, empty builder.
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.

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.
bool IsCreated()

Whether the builder has storage: made by Create(), not the zero value (which cannot change).

Since 0.26

int Length()

The length of the text so far, in bytes.

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).

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.

string Substring(int start)

The text from start to the end, as a new string.

Panics when start is not in 0 to Length().

void Truncate(int length)

Cuts the text to its first length bytes.

Panics when length is not in 0 to Length().

string ToString()

The text as a string.