Str
import "std/text" (included in import "std") · namespace std.text
Str gathers the string functions as static methods that take the string first: Str.trim(s), Str.split(s, ","). Strings cannot change, so every function that "modifies" one returns a new string.
Positions and lengths are in bytes, like s.length and s[i]. For plain ASCII text that is the same as characters; for other text, see What a string is made of.
import "std"
fn main() {
let s = " Hello, Grav world "
let t = Str.trim(s)
print(t)
print(Str.upper(t))
print(Str.contains(t, "Grav"))
print(Str.indexOf(t, "o"))
print(Str.lastIndexOf(t, "o"))
print(Str.startsWith(t, "Hello"))
print(Str.replace(t, "o", "0"))
print(Str.split("a,b,,c", ","))
print(Str.words(t))
print(Str.join(["x", "y", "z"], "-"))
print(Str.substring(t, 7, 4))
print(Str.padLeft("7", 3, "0"))
print(Str.repeat("ab", 3))
print(Str.count("banana", "a"))
print(Str.isDigits("2024"))
print(Str.compare("apple", "banana") < 0)
print(Str.capitalize("grav"))
print(Str.lines("one\ntwo\nthree").size())
}Hello, Grav world
HELLO, GRAV WORLD
true
4
13
true
Hell0, Grav w0rld
["a", "b", "", "c"]
["Hello,", "Grav", "world"]
x-y-z
Grav
007
ababab
3
true
true
Grav
3indexOfand friends return-1when nothing is found.splitkeeps empty pieces;wordssplits on any run of whitespace and drops empty ones.substring(s, start, len)takes a length;slice(s, start, end)takes an end position, likes[start..end].charAt(s, i)returns the byte ati(IndexErrorwhen out of range), andfromChar(code)turns a code point back into a one-character string.
More helpers
replaceFirst, splitN (a limited split), before/after (around a separator), truncate (with "…"), wrap (word wrapping), indent, case conversions (toSnakeCase, toKebabCase, toCamelCase, toPascalCase, titleCase), levenshtein (edit distance, handy for "did you mean?"), commonPrefix, startsWithIgnoreCase and containsIgnoreCase.
import "std"
fn main() {
print(Str.splitN("key=value=more", "=", 2))
print(Str.after("user@example.com", "@"))
print(Str.truncate("A very long title indeed", 12))
print(Str.wrap("the quick brown fox jumps over the lazy dog", 15))
print(Str.toSnakeCase("parseHTTPRequest"))
print(Str.toCamelCase("max_retry_count"))
print(Str.levenshtein("color", "colour"))
}["key", "value=more"]
example.com
A very long…
["the quick brown", "fox jumps over", "the lazy dog"]
parse_http_request
maxRetryCount
1For regular expressions see Regex; for character-level work on non-ASCII text see Utf8.
Bytes, fast
s[i] is the byte at index i (checked against the length), and for (b in s as binary) walks the bytes as a plain loop: no call, copy or reference counting per byte. Both are several times faster than Str.charAt(s, i), which is a call (grav check suggests s[i] for it). s as binary shares the string's bytes, and indexes the same way. Str.indexOfAny(s, "/?#") finds the first of several separators in one pass.
import "std"
fn main() {
let path = "/users/42/posts?page=2"
let digits = 0
for (b in path as binary) { if (b >= 48 && b <= 57) { digits += 1 } }
print("${digits} digits, first byte ${path[0]}, query at ${Str.indexOfAny(path, "?#")}")
}3 digits, first byte 47, query at 15API
class Str
Static members
static fn length(s: string) -> int— The length in bytes (UTF-8: a character may take several).static fn isEmpty(s: string) -> bool— Whether the string is "".static fn isBlank(s: string) -> bool— Empty or only whitespace.static fn equals(a: string, b: string) -> bool— Whether the strings have the same contents (same as ==).static fn equalsIgnoreCase(a: string, b: string) -> bool— Whether the strings are equal ignoring ASCII letter case.static fn compare(a: string, b: string) -> int— <0, 0, >0 like strcmp:xs.sortBy(fn(a, b) => Str.compare(a, b))sorts A-Z.static fn compareIgnoreCase(a: string, b: string) -> int— Like compare, ignoring ASCII letter case.static fn charAt(s: string, i: int) -> int— The byte at index i (bounds-checked; IndexError outside). In a loop,s[i]orfor (b in s as binary)is faster: no call per byte.static fn fromChar(code: int) -> string— A one-character string from a byte value (65 -> "A").static fn isDigits(s: string) -> bool— Whether every character is a digit 0-9 (false for "").static fn isAlpha(s: string) -> bool— Whether every character is an ASCII letter (false for "").static fn isAlphanumeric(s: string) -> bool— Whether every character is an ASCII letter or digit (false for "").static fn isUpper(s: string) -> bool— Whether no letter is lowercase (false for "").static fn isLower(s: string) -> bool— Whether no letter is uppercase (false for "").static fn indexOf(s: string, sub: string) -> int— The byte index of the first occurrence ofsub, or -1.static fn indexOf(s: string, sub: string, from: int) -> int— The byte index of the first occurrence ofsubat or afterfrom, or -1 (no copy made: for scanning a string piece by piece).static fn indexFrom(s: string, sub: string, from: int) -> int— The same as indexOf(s, sub, from).static fn lastIndexOf(s: string, sub: string) -> int— The byte index of the last occurrence ofsub, or -1.static fn contains(s: string, sub: string) -> bool— Whethersuboccurs in the string.static fn indexOfAny(s: string, chars: string) -> int— The index of the first byte ofsthat is one ofchars' bytes, or -1 ("a/b?c", "/?" -> 1): one pass, for splitting on any of several separators.static fn lastIndexOfAny(s: string, chars: string) -> int— The index of the last byte ofsthat is one ofchars' bytes, or -1.static fn count(s: string, sub: string) -> int— How many non-overlapping timessuboccurs (0 for an emptysub).static fn startsWith(s: string, prefix: string) -> bool— Whether the string begins withprefix.static fn endsWith(s: string, suffix: string) -> bool— Whether the string ends withsuffix.static fn concat(a: string, b: string) -> string— The two strings joined (same as a + b).static fn upper(s: string) -> string— ASCII letters made uppercase.static fn lower(s: string) -> string— ASCII letters made lowercase.static fn capitalize(s: string) -> string— The first character made uppercase (ASCII).static fn reverse(s: string) -> string— The bytes in reverse order.static fn repeat(s: string, n: int) -> string— The string repeated n times ("" for n <= 0).static fn substring(s: string, start: int, len: int) -> string—lenbytes starting atstart(bounds are clamped).static fn slice(s: string, start: int, end: int) -> string— Characters [start, end) (bounds are clamped).static fn remove(s: string, start: int, len: int) -> string— The string without thelenbytes starting atstart.static fn removePrefix(s: string, prefix: string) -> string— The string withoutprefixat its start (unchanged when it does not start with it).static fn removeSuffix(s: string, suffix: string) -> string— The string withoutsuffixat its end (unchanged when it does not end with it).static fn trim(s: string) -> string— Without whitespace at both ends.static fn trimStart(s: string) -> string— Without whitespace at the start.static fn trimEnd(s: string) -> string— Without whitespace at the end.static fn replace(s: string, old: string, repl: string) -> string— Every occurrence ofoldreplaced byrepl.static fn padLeft(s: string, len: int, ch: string) -> string— Pad tolencharacters with the first character ofch(a space ifchis empty).static fn padRight(s: string, len: int, ch: string) -> string— Padded on the right tolencharacters with the first character ofch(a space if empty).static fn center(s: string, width: int, ch: string) -> string— Centered inwidthcharacters, padded with the first character ofch(a space if empty).static fn split(s: string, delim: string) -> Array<string>— The parts between occurrences ofdelim("a,,b" by "," gives "a", "", "b").static fn split(s: string, delim: string, limit: int) -> Array<string>— At mostlimitparts, the last keeping the rest (0 or less: no limit): split("k=v=w", "=", 2) == ["k", "v=w"]. The same as splitN.static fn lines(s: string) -> Array<string>— Lines of text (handles \n and \r\n; no trailing empty line for a final newline).static fn words(s: string) -> Array<string>— Whitespace-separated words (no empty entries).static fn join(parts: Array<string>, delim: string) -> string— Joins with one allocation (no quadratic copying).static fn replaceFirst(s: string, old: string, repl: string) -> string—swith only the first occurrence ofoldreplaced.static fn splitN(s: string, delim: string, limit: int) -> Array<string>— Split atdeliminto at mostlimitpieces (the last keeps the rest): splitN("a=b=c", "=", 2) == ["a", "b=c"].static fn before(s: string, sep: string) -> string— The text before the firstsep, or all ofswhen it does not contain one.static fn after(s: string, sep: string) -> string— The text after the firstsep, or "" when it does not contain one.static fn truncate(s: string, max: int) -> string— At mostmaxcharacters, ending in "…" when it was cut.static fn wrap(s: string, width: int) -> Array<string>— The words ofsre-flowed into lines of at mostwidthcharacters (a longer word gets a line of its own).static fn indent(s: string, prefix: string) -> string— Each line ofsprefixed withprefix.static fn identifierWords(s: string) -> Array<string>— The words of an identifier or phrase: "parseHTTPRequest", "parse_http request" and "parse-http" all split into lowercase words.static fn toSnakeCase(s: string) -> string— snake_case: "parseHttpRequest" -> "parse_http_request".static fn toKebabCase(s: string) -> string— kebab-case: "parseHttpRequest" -> "parse-http-request".static fn toCamelCase(s: string) -> string— camelCase: "parse_http_request" -> "parseHttpRequest".static fn toPascalCase(s: string) -> string— PascalCase: "parse_http_request" -> "ParseHttpRequest".static fn titleCase(s: string) -> string— Every word capitalized: "the grav book" -> "The Grav Book".static fn levenshtein(a: string, b: string) -> int— The number of single-character edits (insert, delete, replace) that turn a into b, counted in bytes: levenshtein("kitten", "sitting") == 3.static fn commonPrefix(a: string, b: string) -> string— The longest start that a and b share.static fn startsWithIgnoreCase(s: string, prefix: string) -> bool— Whethersstarts withprefix, ignoring case.static fn containsIgnoreCase(s: string, sub: string) -> bool— Whetherscontainssub, ignoring case.