Grav v1.14.0

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.

grav
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())
}
Output
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
3
  • indexOf and friends return -1 when nothing is found.
  • split keeps empty pieces; words splits on any run of whitespace and drops empty ones.
  • substring(s, start, len) takes a length; slice(s, start, end) takes an end position, like s[start..end].
  • charAt(s, i) returns the byte at i (IndexError when out of range), and fromChar(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.

grav
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"))
}
Output
["key", "value=more"]
example.com
A very long…
["the quick brown", "fox jumps over", "the lazy dog"]
parse_http_request
maxRetryCount
1

For 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.

grav
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, "?#")}")
}
Output
3 digits, first byte 47, query at 15

API

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] or for (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 of sub, or -1.
  • static fn indexOf(s: string, sub: string, from: int) -> int — The byte index of the first occurrence of sub at or after from, 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 of sub, or -1.
  • static fn contains(s: string, sub: string) -> bool — Whether sub occurs in the string.
  • static fn indexOfAny(s: string, chars: string) -> int — The index of the first byte of s that is one of chars' 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 of s that is one of chars' bytes, or -1.
  • static fn count(s: string, sub: string) -> int — How many non-overlapping times sub occurs (0 for an empty sub).
  • static fn startsWith(s: string, prefix: string) -> bool — Whether the string begins with prefix.
  • static fn endsWith(s: string, suffix: string) -> bool — Whether the string ends with suffix.
  • 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 — len bytes starting at start (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 the len bytes starting at start.
  • static fn removePrefix(s: string, prefix: string) -> string — The string without prefix at its start (unchanged when it does not start with it).
  • static fn removeSuffix(s: string, suffix: string) -> string — The string without suffix at 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 of old replaced by repl.
  • static fn padLeft(s: string, len: int, ch: string) -> string — Pad to len characters with the first character of ch (a space if ch is empty).
  • static fn padRight(s: string, len: int, ch: string) -> string — Padded on the right to len characters with the first character of ch (a space if empty).
  • static fn center(s: string, width: int, ch: string) -> string — Centered in width characters, padded with the first character of ch (a space if empty).
  • static fn split(s: string, delim: string) -> Array<string> — The parts between occurrences of delim ("a,,b" by "," gives "a", "", "b").
  • static fn split(s: string, delim: string, limit: int) -> Array<string> — At most limit parts, 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 — s with only the first occurrence of old replaced.
  • static fn splitN(s: string, delim: string, limit: int) -> Array<string> — Split at delim into at most limit pieces (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 first sep, or all of s when it does not contain one.
  • static fn after(s: string, sep: string) -> string — The text after the first sep, or "" when it does not contain one.
  • static fn truncate(s: string, max: int) -> string — At most max characters, ending in "…" when it was cut.
  • static fn wrap(s: string, width: int) -> Array<string> — The words of s re-flowed into lines of at most width characters (a longer word gets a line of its own).
  • static fn indent(s: string, prefix: string) -> string — Each line of s prefixed with prefix.
  • 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 — Whether s starts with prefix, ignoring case.
  • static fn containsIgnoreCase(s: string, sub: string) -> bool — Whether s contains sub, ignoring case.

Edit this page on GitHub