Skip to content

std.string ​

String manipulation module. Except for format, all functions take a read-only borrow of their arguments (&String), and the source string remains usable after the call.

All functions fall back to empty-string semantics when an argument's type does not match (rather than raising an error): split/trim/upper and similar functions treat non-String arguments as "". This means an incorrect argument type will not interrupt execution, but it will also not produce the expected result—rely on the type checker to catch such errors at compile time.

yaoxiang
use std.string

Function Overview ​

FunctionSignature
split(s: &String, sep: &String) -> Vec(String)
trim(s: &String) -> String
upper(s: &String) -> String
lower(s: &String) -> String
replace(s: &String, old: &String, new: &String) -> String
contains(s: &String, sub: &String) -> Bool
starts_with(s: &String, prefix: &String) -> Bool
ends_with(s: &String, suffix: &String) -> Bool
index_of(s: &String, sub: &String) -> Int
substring(s: &String, start: Int, end: Int) -> String
is_empty(s: &String) -> Bool
len(s: &String) -> Int
chars(s: &String) -> Vec(String)
concat(s1: &String, s2: &String) -> String
repeat(s: &String, n: Int) -> String
reverse(s: &String) -> String
format(format: &String, ...args) -> String
parse_int(s: &String) -> Result(Int, Error)
parse_float(s: &String) -> Result(Float, Error)
char_code(s: &String, i: Int) -> Int
from_char_code(n: Int) -> Result(String, Error)

Functions ​

split ​

yaoxiang
split: (s: &String, sep: &String) -> Vec(String)

Split s by sep and return a list of substrings.

  • s — the string to split
  • sep — the separator; an empty string splits the input character by character

Return value: List(String). If the separator is not found, a single-element list is returned.

yaoxiang
use std.assert
use std.list
use std.string

main: () -> Void = {
    parts = string.split("a,b,c", ",")
    assert(list.len(parts) == 3)
    assert(list.get(parts, 0) == "a")

    // Empty separator → split character by character
    cs = string.split("abc", "")
    assert(list.len(cs) == 3)
}

trim ​

yaoxiang
trim: (s: &String) -> String

Remove leading and trailing Unicode whitespace characters.

Return value: a new string with leading and trailing whitespace removed (s is not modified).

yaoxiang
use std.assert
use std.string

main: () -> Void = {
    assert(string.trim("  hi  ") == "hi")
}

upper ​

yaoxiang
upper: (s: &String) -> String

Convert to uppercase (Unicode-aware).

yaoxiang
use std.assert
use std.string

main: () -> Void = {
    assert(string.upper("abc") == "ABC")
}

lower ​

yaoxiang
lower: (s: &String) -> String

Convert to lowercase (Unicode-aware).

yaoxiang
use std.assert
use std.string

main: () -> Void = {
    assert(string.lower("ABC") == "abc")
}

replace ​

yaoxiang
replace: (s: &String, old: &String, new: &String) -> String

Replace all occurrences of old in s with new.

  • old — when empty, s is returned unchanged (nothing is inserted)
yaoxiang
use std.assert
use std.string

main: () -> Void = {
    assert(string.replace("a-b-c", "-", "+") == "a+b+c")
    assert(string.replace("abc", "", "x") == "abc")
}

contains ​

yaoxiang
contains: (s: &String, sub: &String) -> Bool

Whether sub occurs in s. An empty string always returns true.

yaoxiang
use std.assert
use std.string

main: () -> Void = {
    assert(string.contains("hello", "ell"))
    assert(!string.contains("hello", "xyz"))
}

starts_with ​

yaoxiang
starts_with: (s: &String, prefix: &String) -> Bool

Whether s starts with prefix. An empty prefix always returns true.

yaoxiang
use std.assert
use std.string

main: () -> Void = {
    assert(string.starts_with("hello", "he"))
}

ends_with ​

yaoxiang
ends_with: (s: &String, suffix: &String) -> Bool

Whether s ends with suffix. An empty suffix always returns true.

yaoxiang
use std.assert
use std.string

main: () -> Void = {
    assert(string.ends_with("hello", "lo"))
}

index_of ​

yaoxiang
index_of: (s: &String, sub: &String) -> Int

The scalar-value (code point) index of the first occurrence of sub (#385).

Return value: the index if found; -1 if not found.

The return value uses the same coordinate system as substring / char_code / s[i], so these can be used together directly.

yaoxiang
use std.assert
use std.string

main: () -> Void = {
    assert(string.index_of("hello", "ll") == 2)
    assert(string.index_of("hello", "xyz") == -1)
}

substring ​

yaoxiang
substring: (s: &String, start: Int, end: Int) -> String

Extract the [start, end) interval using character indices.

  • start — the starting character index; defaults to 0
  • end — the ending character index (exclusive); defaults to the end of the string

Return value: the extracted substring. Out-of-range bounds are clamped to the valid range without an error; when start > end, the result is clamped to an empty string.

yaoxiang
use std.assert
use std.string

main: () -> Void = {
    assert(string.substring("hello", 1, 4) == "ell")
    assert(string.substring("hello", 1, 99) == "ello")   // Clamp the upper bound
}

is_empty ​

yaoxiang
is_empty: (s: &String) -> Bool

Whether s is an empty string.

yaoxiang
use std.assert
use std.string

main: () -> Void = {
    assert(string.is_empty(""))
    assert(!string.is_empty("x"))
}

len ​

yaoxiang
len: (s: &String) -> Int

Return the number of Unicode scalar values (code points)—the same counting convention as substring / chars / char_code / index_of (#385).

yaoxiang
use std.assert
use std.string

main: () -> Void = {
    assert(string.len("hello") == 5)
    assert(string.len("中") == 1)    // Number of code points, not the number of UTF-8 bytes
}

chars ​

yaoxiang
chars: (s: &String) -> Vec(String)

Split into a list of single-character strings (by Unicode scalar value).

yaoxiang
use std.assert
use std.list
use std.string

main: () -> Void = {
    cs = string.chars("ab")
    assert(list.len(cs) == 2)
    assert(cs[0] == "a")
}

concat ​

yaoxiang
concat: (s1: &String, s2: &String) -> String

Concatenate two strings. You can also use the + operator directly.

yaoxiang
use std.assert
use std.string

main: () -> Void = {
    assert(string.concat("a", "b") == "ab")
}

repeat ​

yaoxiang
repeat: (s: &String, n: Int) -> String

Repeat s n times.

  • n — the number of repetitions; n <= 0 returns an empty string
yaoxiang
use std.assert
use std.string

main: () -> Void = {
    assert(string.repeat("ab", 3) == "ababab")
    assert(string.repeat("ab", 0) == "")
}

reverse ​

yaoxiang
reverse: (s: &String) -> String

Reverse the string character by character.

yaoxiang
use std.assert
use std.string

main: () -> Void = {
    assert(string.reverse("abc") == "cba")
}

format ​

yaoxiang
format: (format: &String, ...args) -> String

Format a string using {index} placeholders, with optional width and alignment specifiers.

Placeholder syntax:

FormMeaning
{0}Argument 0 (arguments after format are numbered from 0)
{0:03}Width 3
{0:>3}Width 3, right-aligned (default)
{0:<3}Width 3, left-aligned
{0:^3}Width 3, centered

A literal brace is represented by doubling it: two left braces produce one literal left brace, and two right braces work the same way.

Return value: the formatted string. Arguments are first converted to strings (as in convert.to_string); an out-of-range index yields an empty string, and an invalid width is treated as 0.

yaoxiang
use std.assert
use std.string

main: () -> Void = {
    assert(string.format("{0}-{1}", "a", "b") == "a-b")
    assert(string.format("[{0:>5}]", "ab") == "[   ab]")
    assert(string.format("[{0:<5}]", "ab") == "[ab   ]")
}

parse_int ​

yaoxiang
parse_int: (s: &String) -> Result(Int, Error)

Parse a decimal integer (leading and trailing whitespace are removed automatically).

Return value: Result.ok(Int) on success; Result.err(Error) on failure, with code set to E6010. Does not throw an error.

yaoxiang
use std.assert
use std.result
use std.string

main: () -> Void = {
    assert(result.is_ok(string.parse_int("42")))
    assert(result.is_err(string.parse_int("abc")))
}

parse_float ​

yaoxiang
parse_float: (s: &String) -> Result(Float, Error)

Parse a floating-point number (leading and trailing whitespace are removed automatically).

Return value: Result.ok(Float) on success; Result.err(Error) on failure, with code set to E6011.

yaoxiang
use std.assert
use std.result
use std.string

main: () -> Void = {
    assert(result.is_ok(string.parse_float("3.14")))
    assert(result.is_err(string.parse_float("xxx")))
}

char_code ​

yaoxiang
char_code: (s: &String, i: Int) -> Int

Get the Unicode code point of the ith character (using the scalar-value metric, in the same domain as chars / substring).

  • s — the source string (read-only borrow)
  • i — the character index (Unicode scalar-value metric, the same unit as index_of)

Return value: the code point; an out-of-range index returns -1 (following the same convention as a failed index_of lookup—code points are nonnegative, so -1 is unambiguous). Does not throw an error.

yaoxiang
use std.assert
use std.string

main: () -> Void = {
    assert(string.char_code("A", 0) == 65)
    assert(string.char_code("中", 0) == 0x4E2D)     // Scalar-value index
    assert(string.char_code("A", 9) == -1)          // Out-of-range access returns -1
}

from_char_code ​

yaoxiang
from_char_code: (n: Int) -> Result(String, Error)

Convert a code point to a single-character string.

  • n — a Unicode code point

Return value: Result.ok(String) on success (a single string); Result.err(Error) for an invalid code point, with code set to E6012. Does not throw an error. Validity is determined using char::from_u32 (src/std/string.rs:613-619), following the same rules as the lexer-level \u{…} escape: negative numbers, the surrogate range (U+D800–U+DFFF), and values greater than U+10FFFF are all invalid. U+10000..=U+10FFFF directly produces a valid 4-byte UTF-8 sequence, while UTF-16 surrogate-pair composition is left to the yx layer.

yaoxiang
use std.assert
use std.result
use std.string

main: () -> Void = {
    assert(result.unwrap(string.from_char_code(65)) == "A")
    assert(result.unwrap(string.from_char_code(0x4E2D)) == "中")

    // Invalid code points take the Err branch
    assert(result.is_err(string.from_char_code(-1)))
    assert(result.code(result.unwrap_err(string.from_char_code(-1))) == "E6012")

    // Inverse of char_code
    assert(result.unwrap(string.from_char_code(string.char_code("A", 0))) == "A")
}
  • std.convert — number-to-string conversion
  • std.result — unwrap the results of parse_* / from_char_code
  • std.json — the Unicode primitives used for string escaping come from this module