Grav v1.14.0

StringBuilder

import "std/text" (included in import "std") · namespace std.text

A StringBuilder builds a string piece by piece in one growing buffer. Building text in a loop with s += piece copies the whole string on every step, which gets slow for long text; a builder appends in amortised O(1) and creates the string once, at toString().

Most methods return the builder itself, so calls chain.

grav
import "std"

fn main() {
    let sb = new StringBuilder()
    sb.append("<ul>").appendLine("")
    for (item in ["tea", "milk"]) {
        sb.append("  <li>").append(item).appendLine("</li>")
    }
    sb.append("</ul>")
    print(sb.toString())

    let csv = new StringBuilder()
    for (i in 1..=5) {
        if (!csv.isEmpty()) { csv.append(",") }
        csv.appendInt(i * i)
    }
    print(csv)
    print(csv.length())
    csv.truncate(4)
    print(csv)
}
Output
<ul>
  <li>tea</li>
  <li>milk</li>
</ul>
1,4,9,16,25
11
1,4,

append takes strings and, through an overload, any other value (shown as print would). appendChar adds a code point, insert puts text at a byte position, and print(sb) prints the contents.

API

class StringBuilder

Constructors

  • new StringBuilder()

Methods

  • fn append(s: string) -> StringBuilder — Appends text; returns this builder (calls chain).
  • fn appendLine(s: string) -> StringBuilder — Appends text and a newline; returns this builder.
  • fn appendInt(n: long) -> StringBuilder — Appends a number; returns this builder.
  • fn appendFloat(f: double) -> StringBuilder — Appends a number (shortest exact form); returns this builder.
  • fn appendBool(b: bool) -> StringBuilder — Appends "true" or "false"; returns this builder.
  • fn append(value: any) -> StringBuilder — Any value, formatted like print()/str().
  • fn insert(at: int, s: string) -> StringBuilder — Inserts text at a byte offset (clamped to the current length).
  • fn truncate(n: int) -> StringBuilder — Keeps only the first n bytes.
  • fn reserve(n: int) — Pre-allocates room for n more bytes.
  • fn appendChar(c: int) -> StringBuilder — Appends one byte (e.g. 10 for a newline, 65 for 'A').
  • fn repeat(s: string, times: int) -> StringBuilder — Appends s times times; returns this builder.
  • fn length() -> int — The length in bytes so far.
  • fn isEmpty() -> bool — Whether nothing has been appended.
  • fn clear() — Empties the builder (keeping its buffer).
  • fn toString() -> string — A fresh copy of the contents (the builder stays usable).

Edit this page on GitHub