---
title: "Strings"
description: "UTF-8 text, characters, searching, splitting, transformation, and borrowed byte views."
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.atoll.workreef.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Strings

`string` is owned, immutable UTF-8 text. `char` is one Unicode scalar value.
`s[a..b]` is a borrowed byte view into a string that costs nothing to
create (`s.get(a..b)` answers it as a `string?`); `substring(start, end)` is the owning copy of the same bytes.

```atoll run=10
fn main() int {
    name: string = "Ångström"
    return name.len()        // 10 bytes — 8 characters, two of them two bytes
}
```

**`len()` is bytes.** It reads the encoded byte count and is O(1). There is no
character count and no character index; on ASCII the two views agree, which is
what makes the difference easy to miss. See [Known gaps](#known-gaps).

The everyday surface — `first`, `last`, `take`, `drop` (windows over the same bytes, like `s[a..b]`; `clone()` owns its bytes), `map`, `filter`,
`fold`, `count`, `lines`, `words`, `chars`, `pad_start`, `is_blank`,
`split_with_limit`, `string.join` and more — is written in Atoll, in
`stdlib/string.at`; `atoll doc --std string` lists every method.
[Known gaps](#known-gaps) says what remains: the full-Unicode case operations,
which need tables.

## Characters and safe access

Every accessor that could run off the end answers an `Option`, so text handling
never panics and never needs a hand-written bounds check.

**Access is by byte, not by character.** `get(index)` answers a `byte?`:

```atoll run=104
fn main() int {
    text: string = "hello"
    return match text.get(0) { Some(b) => int(b) None => 0 }   // 'h' is 104
}
```

`len()` is bytes. `get`, `substring` and `slice` are byte-indexed. There
is no character index: an index should be the cheap one. On ASCII a byte
and a character agree, which is exactly what makes the difference easy to
miss.

Indexing with `[]` is not available on `string` at all — the byte/character
ambiguity would be silent, so the language does not offer it:

```atoll fail
fn first_char(text string) char {
    return text.get(0)
}
```

`char`'s classification takes Rust's split: the plain names are Unicode's,
and the `_ascii` forms are ASCII's alone. Each answers as Rust's `char` method
of the same name does, from Unicode 18.0.0, the version Rust 1.100 carries.

- `is_whitespace` is the White_Space property: the ASCII six (space, tab, line
  feed, vertical tab, form feed, carriage return) and NEL, the no-break spaces,
  the Ogham space mark, U+2000 to U+200A, the line and paragraph separators,
  the medium mathematical space and the ideographic space.
  `is_ascii_whitespace` is space, tab, line feed, form feed and carriage
  return, and not the vertical tab.
- `is_alphabetic` is the Alphabetic property: the letters of every script, the
  letter numbers such as the Roman numerals, and the marks that are part of a
  letter, such as most vowel signs, but not a combining accent.
  `is_ascii_alphabetic` is `A`-`Z` and `a`-`z`.
- `is_numeric` is every number, the general categories Nd, Nl and No: the
  digits of every script, the Roman numerals, superscripts and fractions.
  `is_ascii_digit` is `0`-`9`, and so is `is_digit`, as Rust's `is_digit(10)`.
- `is_alphanumeric` is `is_alphabetic` or `is_numeric`, and
  `is_ascii_alphanumeric` is `is_ascii_alphabetic` or `is_ascii_digit`.
- `is_ascii_upper_case` is `A`-`Z`, and `is_ascii_lower_case` `a`-`z`.

The pair `to_lower_ascii` / `to_upper_ascii` turn `A`-`Z` / `a`-`z` alone and
return any other character unchanged; `to_u32`, `to_int` and `to_string`
convert.

Unicode's case is the `text` module's. A file that has `import text` has four
more methods on `char`, and two on `string` ([Case](#case)):

- `is_upper_case` is the Uppercase property and `is_lower_case` the Lowercase
  one: the capital and small letters of every script, and characters such as
  `ª`, the circled letters and the Roman numerals; a titlecase letter such as
  `ǅ` is neither.
- `to_lower` and `to_upper` map the character as Rust's `to_lowercase` and
  `to_uppercase` do, and answer a `text.CaseIter`: the one character it
  becomes, the character itself where it has no other case, or the two or
  three Unicode maps it to (`'ß'.to_upper()` is `S`, `S`; `'İ'.to_lower()` is
  `i` and a combining dot). It is an iterator of `char`, and `to_string()`
  writes it out.

A character below U+0080 is answered by a compare or two; only one at or above
it reads a table, so ASCII text costs what it did when the names were ASCII's.

```atoll run=53
fn main() int {
    word := "Größe"
    letters := word.chars().filter(c => c.is_alphabetic()).count()
    ascii := word.chars().filter(c => c.is_ascii_alphabetic()).count()
    return letters * 10 + ascii
}
```

```atoll
fn main() void {
    println("${'٣'.is_numeric()} ${'٣'.is_ascii_digit()}")      // true false
    println("${'Ⅻ'.is_alphabetic()} ${'Ⅻ'.is_numeric()}")  // true true
    println("${'²'.is_numeric()} ${'²'.is_alphabetic()}")  // true false
    println("${'λ'.is_alphabetic()} ${'λ'.is_ascii_alphabetic()}")  // true false
}
```

```atoll
import text

fn main() void {
    println("${'Λ'.is_upper_case()} ${'Λ'.is_ascii_upper_case()}")  // true false
    println("${'ß'.to_upper()} ${'ß'.to_upper().count()}")         // SS 2
    println("${'Σ'.to_lower()} ${'É'.to_lower_ascii()}")           // σ É
}
```

Walking bytes, as the next section does, asks the ASCII question:

```atoll
fn is_identifier(text string) bool {
    if text.is_empty() { return false }
    match text.get(0) {
        None => return false
        Some(head) => if !head.is_ascii_alphabetic() && head.to_char() != '_' { return false }
    }
    for c in text {
        if !c.is_ascii_alphanumeric() && c.to_char() != '_' { return false }
    }
    return true
}

fn main() void {
    println("${is_identifier("total_count")}")   // true
    println("${is_identifier("9lives")}")        // false
    println("${is_identifier("")}")              // false
}
```

`char.from_u32` rejects surrogates and anything above `U+10FFFF`:

```atoll
fn decode_escape(codepoint u32) string {
    match char.from_u32(codepoint) {
        Some(c) => return c.to_string()
        None => return "?"
    }
}

fn main() void {
    println(decode_escape(9731u32))         // ☃
    println(decode_escape(0xD800u32))       // ? — lone surrogate
}
```

## Iterating bytes

`for c in text` walks the **bytes**, in place and without allocating a list,
and binds a `byte`. That is the same answer `text[i]` and `text.get(i)` give,
and it has to be: a loop that yielded `char` where subscripting yields `byte`
would make one of the two a miscompile.

So the classification set — `is_digit`, `is_alphabetic`, `is_alphanumeric`,
`is_whitespace`, the `_ascii` forms `is_ascii_digit`, `is_ascii_alphabetic`,
`is_ascii_alphanumeric` and `is_ascii_whitespace`, and the `to_lower_ascii` /
`to_upper_ascii` pair — is on `byte` as well as on `char`, at the width a
string is actually walked, and so are `is_upper_case` and `is_lower_case`, with
no import. On a `byte` every one of them is ASCII: a plain name answers the
ASCII part of `char`'s, so `is_alphabetic` is `A`-`Z` and `a`-`z`,
`is_upper_case` `A`-`Z` and `is_whitespace` the ASCII six White_Space has, the
vertical tab among them. A byte at or above 128
is part of a character, not one, so `é`'s two bytes are not letters there and a
no-break space's two bytes are not whitespace; decode with `chars()` to ask the
character. `to_char()` is the one step up when you want a codepoint: a
comparison against a character literal, or `to_string()`. It reads a byte as
the codepoint of the same number, so `to_char()` of a byte at or above 128 is
a Latin-1 character, not the character the byte is part of.

A byte above 127 is one unit of a multi-byte sequence and is not a character,
so every predicate answers `false` for it. Text that is not ASCII has to be
decoded before "is this a letter" means anything.

`bytes()` is the same walk as a lazy iterator, for a chain:
`text.bytes().filter(p).count()` reads each byte where it sits and builds
nothing. `enumerate()` numbers the bytes by their offset, so
`for (i, b) in text.enumerate()` binds each byte beside its position.
`.collect()` builds a `[]byte`; `to_bytes()` is the same copy, spelled as a
conversion. `count`, `any`, `all`, `none` and `fold` take a function of a byte
directly, and `map` and `filter` build a new string.

```atoll
fn main() void {
    text := "a1b2c3"
    println("${text.bytes().filter(b => b.is_ascii_digit()).count()}")    // 3
    for (i, b) in text.enumerate() {
        if b.is_ascii_digit() { println("digit at ${i}") }                 // 1, 3, 5
    }
}
```

The loop itself is the workhorse:

```atoll
fn digit_sum(text string) int {
    mut total := 0
    for c in text {
        if c.is_ascii_digit() {
            total = total + (c.to_int() - '0'.to_int())
        }
    }
    return total
}

fn main() void {
    println("${digit_sum("a1b2c3")}")    // 6
}
```

A filtering pass appends into a `mut string`, which is the substitute for both
`filter` and `map`:

```atoll
fn strip_punctuation(text string) string {
    mut out := ""
    for c in text {
        if c.is_ascii_alphanumeric() || c.is_ascii_whitespace() {
            out.append_string(c.to_char().to_string())
        }
    }
    return out
}

fn count_where(text string, keep fn(byte) -> bool) int {
    mut n := 0
    for c in text {
        if keep(c) { n = n + 1 }
    }
    return n
}

fn main() void {
    println(strip_punctuation("hello, world!"))       // hello world
    println("${count_where("banana", c => c.to_char() == 'a')}")   // 3
    println("${count_where("hello", c => "aeiou".contains(c.to_char().to_string()))}")
}
```

Materializing a `[]char` is `chars().collect()` (below). Reach for it only
when you need random access or a second pass:

```atoll
fn reversed(text string) string {
    chars: []char = text.chars().collect()
    mut out := ""
    mut i := chars.len() - 1
    for i >= 0 {
        out.append_string((chars.get(i.to_usize()) ?? ' ').to_string())
        i = i - 1
    }
    return out
}

fn main() void {
    println(reversed("stressed"))    // desserts
}
```

## Iterating characters

`chars()` decodes the text into `char`s as they are asked for. It is a lazy
iterator, as Rust's `chars()` is: nothing is decoded until a loop, a consumer
or `collect()` runs it. The walk ends at the end of the text, or at the first
byte that does not begin a whole character.

A `for` loop over it, and a pipeline over it consumed where it is written, is
one loop over the bytes. A byte below 128 is its own character, and nothing is
allocated:

```atoll run=8
fn main() int {
    word := "Ångström"
    mut n := 0
    for c in word.chars() {
        if c.to_u32() > 0u32 { n = n + 1 }
    }
    return n              // 8 characters in 10 bytes
}
```

```atoll
fn main() void {
    text := "Ünïcödé, plain"
    println("${text.chars().count()}")                                    // 14
    println("${text.chars().filter(c => c.to_u32() > 127u32).count()}")   // 4
    println("${text.chars().any(c => c.is_ascii_upper_case())}")          // false
}
```

`.collect()` builds a `[]char`. Using `chars()` where a list is expected is an
error whose fix writes the `.collect()`; see
[Iteration](https://docs.atoll.workreef.dev/language/standard-library/iteration/).

## Searching

`contains`, `starts_with`, and `ends_with` return `bool`. `index_of` and
`last_index_of` return `CharIndex?`.

```atoll
fn is_json_request(path string, accept string) bool {
    return path.starts_with("/api/") && accept.contains("application/json")
}

fn extension(filename string) string {
    match filename.last_index_of(".") {
        None => return ""
        Some(dot) => {
            rest := filename.get(dot + 1..filename.len().to_usize())
            return rest?.to_string() ?? ""
        }
    }
}

fn main() void {
    println("${is_json_request("/api/users", "application/json")}")
    println(extension("archive.tar.gz"))    // gz
    println("[${extension("README")}]")     // []
}
```

Truncation is a slice, not a `take` — clamp the length yourself and keep the
result on a byte boundary you control:

```atoll
fn truncate(text string, limit int) string {
    if text.len() <= limit { return text }
    keep: usize = (limit - 1).to_usize()
    return "${text.get(0..keep)?.to_string() ?? ""}…"
}

fn main() void {
    println(truncate("a very long headline indeed", 12))
    println(truncate("short", 12))
}
```

Plain `==` is content equality, and `compare_to` is the lexicographic
byte-order comparison behind sorting, answering an `Ordering`.

```atoll run=1
fn main() int {
    if "abc" == "abc" { return 1 }
    return 0
}
```

Ordering comparison — `<`, `compare_to` — is lexicographic byte order and
lowers. Case-insensitive comparison is ASCII-only:
`equals_ignore_case` / `compare_to_ignore_case`. Full Unicode case mapping
is not in the stdlib — see [Known gaps](#known-gaps).

## Slicing: byte views

`s[a..b]` is **byte**-indexed, stops the program out of range, and `s.get(a..b)`
returns `&string?` — a window over the parent's bytes. It allocates
nothing. An end may be left out: `s[a..]`, `s[..b]`, `s[..=b]` and `s[..]`. `substring(start,
end)` is also byte-indexed and returns `string?`, but it **copies**. There
is no `substring` type.

```atoll
fn main() void {
    record := "id=42;name=ada"
    match record.get(0..5) {
        None => println("too short")
        Some(view) => {
            println("${view.len()} ${view.is_empty()}")
            println("${view.get(3..5)?.to_string() ?? ""}")   // 42
            println("${view.to_bytes().len()} ${view.to_bytes().len()}")
            println(view.to_string())                                  // id=42
        }
    }
}
```

`substring` returns `string?`, so a function that promises `string` has to
discharge the `None`:

```atoll fail
fn prefix(text string) string {
    return text.substring(0, 2)
}
```

A window is a `&string`: every read a string has, and it lives no longer than
the string it came from. `clone()` is a string of its own, and `to_bytes()`
answers `[]byte`.
Out-of-bounds ranges give `None`; the range endpoints are **not** checked for
UTF-8 character boundaries, so only decode a view whose byte range you know
is aligned. Splitting `"Ångström"` at byte 1 lands mid-sequence:

```atoll
fn main() void {
    name := "Ångström"
    println("${name.get(0..2)?.to_string() ?? "?"}")   // Å — 2 bytes
    println("${name.get(0..1)?.to_string() ?? "?"}")   // split codepoint
    println("${name.get(0) ?? 0u8}")                     // 195 — the FIRST BYTE
}
```

**It is `slice` that borrows, not `substring`.** `substring` calls `copy_bytes`
and hands back storage of its own, which is why it costs the copy. A `slice`
window is a `&string`, so hold one inside the parent's scope and call `clone()`
(or `to_bytes()`) when the value must outlive it. `ATOLL1116` refuses a window
that leaves the function owning its bytes.

## Splitting

`split(separator)` finds the parts between separators as they are asked for,
and preserves empty segments, exactly like Python and Rust. Like `chars()`, it
is a lazy iterator. A `for` loop over it, and a pipeline over it consumed where
it is written, walk the string with nothing allocated. Each part is a window
over the string's bytes (above), and `.collect()` builds a `[]&string`: no text
is copied, and the list lives no longer than the string. Where the parts must
stay past it, `.map(p => p.clone()).collect()` builds the `[]string`.
`lines()` and `words()` are iterators too, and so is
`split_with_limit(separator, limit)`: at most `limit` parts, the last of them
the rest of the string, separators and all.

```atoll
fn main() void {
    println("${"a,b,,c".split(",").count()}")    // 4 — empty segment preserved
    for part in "key=a=b".split_with_limit("=", 2) {
        println(part)                            // key, then a=b
    }
    for line in "one\ntwo\n\nthree".split("\n") {
        if line.trim().is_empty() { continue }
        println(line)
    }
}
```

Split-once — the `key=value` case where the value may itself contain the
separator — is `index_of` plus two slices:

```atoll
fn split_once(text string, sep string) (string, string)? {
    match text.index_of(sep) {
        None => return None
        Some(at) => {
            head := text.get(0..at)?.to_string() ?? ""
            after := at + sep.len().to_usize()
            tail := text.get(after..text.len().to_usize())?.to_string() ?? ""
            return Some((head, tail))
        }
    }
}

fn main() void {
    match split_once("dsn = postgres://host/db?x=1", "=") {
        Some(pair) => println("${pair.0.trim()} -> ${pair.1.trim()}")
        None => println("no separator")
    }
    match split_once("nope", "=") {
        Some(pair) => println("${pair.0}")
        None => println("no separator")
    }
}
```

`words()` splits on whitespace *runs*, which `split(" ")` does not, and drops
the empty segments; whitespace is `char.is_whitespace`'s, so a no-break space
or an ideographic space separates words, as in Rust's `split_whitespace`. `lines()` splits on `\n`, takes a `\r` before it as part of
the break, and does not begin an empty line after a final newline:

```atoll
fn main() void {
    for w in "  the   quick\tbrown  ".words() {
        println("[${w}]")                                   // [the] [quick] [brown]
    }
    text := "id,name\r\n1,ann\r\n2,bo\r\n"
    println("${text.lines().count()}")                     // 3
    rows: []&string = text.lines().collect()
    println("${rows.len()} ${rows.get(1) ?? ""}")              // 3 1,ann
}
```

Each word is a window over the text's bytes, lent from it, as each part of a
`split` is: a loop that only reads a word owes nothing for it, and a word lives
no longer than its text. When one must stay past it, `w.clone()` makes a new
block holding the word's bytes.

```atoll
fn first_word(text string) string {
    for w in text.words() {
        return w.clone()        // its own block: `text` can go
    }
    return ""
}

fn main() void {
    println("${first_word("alpha beta gamma")}")
}
```

## Transformation

`trim`, `trim_start` and `trim_end` remove whitespace, Unicode's as
`char.is_whitespace` answers it, and share the string's bytes: what is left is
a window, as a `split` part is. `trim_ascii`, `trim_start_ascii` and
`trim_end_ascii` remove ASCII whitespace alone, as Rust's `trim_ascii` does
(not the vertical tab), and leave a no-break space or any other character at or
above U+0080 where it is. On ASCII text the two cost the
same: a character above U+007F is decoded only where a scan stops on one.

```atoll run=5
fn main() int {
    padded: string = "  hello  "
    return padded.trim().len()
}
```

```atoll
fn main() void {
    nbsp := "\u{a0}price\u{a0}"
    println("${nbsp.trim().len()} ${nbsp.trim_ascii().len()}")   // 5 9
    wide := "\u{3000}word\u{2028}"
    println("[${wide.trim()}]")                                  // [word]
}
```

### Case

`to_lower_ascii` and `to_upper_ascii` turn `A`-`Z` / `a`-`z` alone and pass
every other byte through. The receiver is not modified.

`to_lower` and `to_upper`, Unicode's, are the `text` module's: a file has them
with `import text`, and a program that never imports it carries none of their
code. They map every character as Rust's `str::to_lowercase` and
`str::to_uppercase` do. A character may become two or three (`ß` raised is
`SS`, `ﬁ` is `FI`), so the answer can be longer or shorter than the text, and
`Σ` lowered is `ς` where it ends a word and `σ` elsewhere. Text that is all
ASCII is turned sixteen bytes at a time, as the `_ascii` forms turn it; text
with a byte at or above 0x80 is mapped whole by the host. A byte that begins no
character is kept as it is.

```atoll run=42
import text

fn main() int {
    if "Straße".to_upper() == "STRASSE" && "ΟΔΟΣ ΣΑΣ".to_lower() == "οδος σας" {
        return 42
    }
    return 7
}
```

```atoll run=42
fn main() int {
    tag: string = "AbC1"
    if tag.to_lower_ascii() == "abc1" && tag.to_upper_ascii() == "ABC1" {
        return 42
    }
    return 7
}
```

`repeat(n usize)` concatenates `n` copies, and `repeat_to(n, &mut out)` appends
them to `out` with one reserve. A count is a `usize`, as an index is, so a
computed one says how it got there: `" ".repeat((width - s.len()).to_usize())`.
An answer longer than a string holds (`u32.MAX` bytes) stops the program rather
than wrapping. `replace` rewrites every
non-overlapping occurrence, left to right, and an empty pattern changes
nothing.

```atoll run=42
fn main() int {
    if "ab".repeat(3) == "ababab" && "a-b-c".replace("-", "+") == "a+b+c" {
        return 42
    }
    return 7
}
```

`pad_start` and `pad_end` widen a string to a byte count with a pad byte; there
is no title case.

For reshaping text there are also `trim`, `trim_start`, `trim_end`,
`substring`, `slice`, `split`, and `to_bytes` when you need to work a byte at a
time.


## Building strings

**`+` does not join two strings.** A concatenation allocates, so it is written
as what it is: an interpolation, `"${a}${b}"`, or `append` into a `mut string`,
which grows it in place — `s += t` is the same append. A list of strings is
joined with `join`, and a list of anything else with `join_of`:

```atoll
fn csv_row(fields []string) string {
    mut out := ""
    for i, field in fields.enumerate() {
        if i > 0 { out.append(",") }
        out.append(field)
    }
    return out
}

fn main() void {
    first := "Ada"
    last := "Lovelace"
    println("${first} ${last}")                              // Ada Lovelace
    println(["a", "b", "c"].join(", "))                      // a, b, c
    println(csv_row(["id", "name", "email"]))                 // id,name,email
    println([1, 2, 3].join_of(" ", v => "#${v}"))            // #1 #2 #3
}
```

`a + b` on two strings is `ATOLL2003`, and its help says the same.

A string that is built over and over keeps its room. `reserve(n)` makes room
for `n` more bytes up front, `append` and `append_int` write into it, and
`clear()` empties the string without giving the room back:

```atoll run=64
fn main() int {
    mut line := ""
    line.reserve(64)
    mut i := 0
    for i < 3 {
        line.clear()
        line.append("row ")
        line.append_int(i)
        i = i + 1
    }
    return line.capacity()
}
```

When you are assembling large output byte by byte — a serializer, a protocol
frame — build into a `mut []byte` instead and decode once at the end. See
[Bytes](https://docs.atoll.workreef.dev/language/standard-library/bytes/).

## Conversion

| From | To | Method | Status |
| --- | --- | --- | --- |
| `string` | `int?` / `float?` | `to_int`, `to_float` | lowers |
| `string` | `bool ! ParseBoolError` | `to_bool` | lowers |
| `string` | `[]byte` (owned copy) | `to_bytes` | lowers |
| `string` | `string?` (borrowed view) | `get(range)`, or `s[range]` | lowers |
| `string` | `CharsIter` (lazy; `.collect()` builds a `[]char`) | `chars` | lowers |
| `List[char]` | `string` | `string.from_chars` | lowers |
| `[]byte` | `string ! Utf8Error` | `string.from_utf8` | lowers |
| `string` | `bytes ! DecodeError` | `decode_hex`, `decode_base64`, `decode_base64_url`, `decode_base32` (and `_to` forms that append to a list you own) | lowers |

The borrowed view is `get(range)` (`s[range]` stops the program out of range). It is a `&string`, a window over the string's own bytes: it copies nothing and lives no longer than the string.

The parsers are total: malformed or out-of-range text yields `None` rather than
a fallback or a hidden exception. `to_int` reads what Rust's `str::parse::<i64>`
reads — an optional `+` or `-`, then one or more ASCII digits and nothing else,
so `" 1"` and `"+"` are `None` and `"-9223372036854775808"` is `int.MIN` — and
it is written in the standard library, so reading a number makes no call out of
the program.

The four **decoders** are total in the same way, and strict beyond it: they
refuse a character outside their alphabet, a length no encoding produces,
padding that does not reach a group boundary, and a tail carrying bits the
encoder could never have set. The encoders they undo are methods on `[]byte`
— see [Encodings](https://docs.atoll.workreef.dev/language/standard-library/bytes/#encodings), which is where
the whole pair is documented.

```atoll
fn main() void {
    signature := "3q2+7w=="
    match signature.decode_base64().ok() {
        Some(raw) => println("${raw.len()} bytes")
        None => println("not base64")
    }
}
```

```atoll
error SettingError { Invalid { key: string } }

fn read_int(raw string, key string) int ! SettingError {
    match raw.trim().to_int().ok() {
        Some(v) => return v
        None => error Invalid { key: key }
    }
}

fn read_flag(raw string) bool {
    normalized := raw.trim()
    return normalized == "true" || normalized == "1" || normalized == "yes"
}

fn main() void {
    match read_int(" 8080 ", "port") {
        Ok(v) => println("${v}")
        Err(e) => println("invalid")
    }
    match read_int("12abc", "port") {
        Ok(v) => println("${v}")
        Err(e) => println("invalid")
    }
    println("${read_flag(" YES ")} ${read_flag("off")}")
}
```

Bytes back to text goes through `string.from_utf8`, which validates strictly —
overlong encodings, surrogates, truncated sequences, stray continuation bytes,
and values above `U+10FFFF` are all rejected:

```atoll
error WireError { NotUtf8 }

fn decode_frame(payload []byte) string ! WireError {
    match string.from_utf8(payload) {
        Ok(text) => return text
        Err(_) => error NotUtf8
    }
}

fn main() void {
    payload := "hi".to_bytes()
    println("${payload.is_valid_utf8()}")
    match decode_frame(payload) {
        Ok(text) => println(text)
        Err(e) => println("not utf-8")
    }
}
```

`bytes()` borrows the string's storage with no copy; `to_bytes()` allocates an
owned list. Choose based on whether the result must outlive the string.

## A worked example

A header-block parser: searching for the colon, byte slicing on either side of
it, ASCII case normalization for the name, and a typed error for the malformed
line.

```atoll
struct Header { name string, value string }

error HeaderError { Malformed { line: string } }

fn parse_header(line &string) Header ! HeaderError {
    match line.index_of(":") {
        None => error Malformed { line: line.clone() }
        Some(colon) => {
            raw_name := line.get(0..colon)?.to_string() ?? ""
            raw_value := line.get(colon + 1..line.len().to_usize())?.to_string() ?? ""
            name := raw_name.trim()
            if name.is_empty() { error Malformed { line: line.clone() } }
            return Header { name: name.clone(), value: raw_value.trim().clone() }
        }
    }
}

fn parse_headers(block string) []Header ! HeaderError {
    mut out: []Header = []
    for line in block.split("\n") {
        if line.trim().is_empty() { continue }
        out.push(parse_header(line)?)
    }
    return out
}

fn lookup(headers []Header, name string) string? {
    wanted := name.trim()
    return headers.find(h => h.name == wanted).map(h => h.value.clone())
}

fn main() void {
    block := "Content-Type: application/json\nX-Request-Id: abc123\n"
    match parse_headers(block) {
        Err(e) => println("malformed header block")
        Ok(headers) => {
            for h in headers {
                println("${h.name} = ${h.value}")
            }
            println("json? ${lookup(headers, "Content-Type") ?? "none"}")
        }
    }

    match parse_headers("no colon here\n") {
        Err(e) => println("malformed header block")
        Ok(headers) => println("${headers.len()}")
    }
}
```

## Characters and codepoints

`len()` is bytes and `get(i)` is byte-indexed, and both stay that way: an
index should be the cheap one. `char` is a Unicode scalar value used for
literals and classification (`is_alphabetic`, `is_numeric`, …); it is not an
indexing type. Walk the bytes, or decode a scalar from a `byte`
with `to_char()` when you have one.

`reversed()` walks scalars — reversing the bytes of UTF-8 is not UTF-8.
`string.from_utf8(bs)` is `string ! Utf8Error` (`Err` carries the offset of the first
ill-formed sequence if the bytes are not well-formed UTF-8).

The higher-order set — `map`, `filter`, `fold`, `count`, `any`, `all`,
`none`, `enumerate` — is over **bytes**, and the doc comment on each says so.

## Known gaps

Everything above marked `run=` is compiled and executed by the compiler's own
test suite. What is left out is left out on purpose:

| missing | why, and what to write instead |
|---|---|
| `title_case`, `capitalize` | word-boundary rules, and a character's titlecase, which is not always its uppercase (`ǆ`'s is `ǅ`, not `Ǆ`); `char.to_upper` raises one. |

`equals_ignore_case` and `compare_to_ignore_case` fold **ASCII**, as Rust's
`eq_ignore_ascii_case` does: Unicode's case folding is a table of its own,
which `to_lower` is not.

Source: https://docs.atoll.workreef.dev/language/standard-library/strings/index.mdx
