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.
use std.stringFunction Overview
| Function | Signature |
|---|---|
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
split: (s: &String, sep: &String) -> Vec(String)Split s by sep and return a list of substrings.
s— the string to splitsep— 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.
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
trim: (s: &String) -> StringRemove leading and trailing Unicode whitespace characters.
Return value: a new string with leading and trailing whitespace removed (s is not modified).
use std.assert
use std.string
main: () -> Void = {
assert(string.trim(" hi ") == "hi")
}upper
upper: (s: &String) -> StringConvert to uppercase (Unicode-aware).
use std.assert
use std.string
main: () -> Void = {
assert(string.upper("abc") == "ABC")
}lower
lower: (s: &String) -> StringConvert to lowercase (Unicode-aware).
use std.assert
use std.string
main: () -> Void = {
assert(string.lower("ABC") == "abc")
}replace
replace: (s: &String, old: &String, new: &String) -> StringReplace all occurrences of old in s with new.
old— when empty,sis returned unchanged (nothing is inserted)
use std.assert
use std.string
main: () -> Void = {
assert(string.replace("a-b-c", "-", "+") == "a+b+c")
assert(string.replace("abc", "", "x") == "abc")
}contains
contains: (s: &String, sub: &String) -> BoolWhether sub occurs in s. An empty string always returns true.
use std.assert
use std.string
main: () -> Void = {
assert(string.contains("hello", "ell"))
assert(!string.contains("hello", "xyz"))
}starts_with
starts_with: (s: &String, prefix: &String) -> BoolWhether s starts with prefix. An empty prefix always returns true.
use std.assert
use std.string
main: () -> Void = {
assert(string.starts_with("hello", "he"))
}ends_with
ends_with: (s: &String, suffix: &String) -> BoolWhether s ends with suffix. An empty suffix always returns true.
use std.assert
use std.string
main: () -> Void = {
assert(string.ends_with("hello", "lo"))
}index_of
index_of: (s: &String, sub: &String) -> IntThe 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.
use std.assert
use std.string
main: () -> Void = {
assert(string.index_of("hello", "ll") == 2)
assert(string.index_of("hello", "xyz") == -1)
}substring
substring: (s: &String, start: Int, end: Int) -> StringExtract the [start, end) interval using character indices.
start— the starting character index; defaults to0end— 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.
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
is_empty: (s: &String) -> BoolWhether s is an empty string.
use std.assert
use std.string
main: () -> Void = {
assert(string.is_empty(""))
assert(!string.is_empty("x"))
}len
len: (s: &String) -> IntReturn the number of Unicode scalar values (code points)—the same counting convention as substring / chars / char_code / index_of (#385).
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
chars: (s: &String) -> Vec(String)Split into a list of single-character strings (by Unicode scalar value).
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
concat: (s1: &String, s2: &String) -> StringConcatenate two strings. You can also use the + operator directly.
use std.assert
use std.string
main: () -> Void = {
assert(string.concat("a", "b") == "ab")
}repeat
repeat: (s: &String, n: Int) -> StringRepeat s n times.
n— the number of repetitions;n <= 0returns an empty string
use std.assert
use std.string
main: () -> Void = {
assert(string.repeat("ab", 3) == "ababab")
assert(string.repeat("ab", 0) == "")
}reverse
reverse: (s: &String) -> StringReverse the string character by character.
use std.assert
use std.string
main: () -> Void = {
assert(string.reverse("abc") == "cba")
}format
format: (format: &String, ...args) -> StringFormat a string using {index} placeholders, with optional width and alignment specifiers.
Placeholder syntax:
| Form | Meaning |
|---|---|
{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.
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
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.
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
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.
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
char_code: (s: &String, i: Int) -> IntGet 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 asindex_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.
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
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.
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")
}Related
std.convert— number-to-string conversionstd.result— unwrap the results ofparse_*/from_char_codestd.json— the Unicode primitives used for string escaping come from this module
