Skip to content

std::strings

Text. A String is immutable UTF-8 text, and this module holds the functions that work on one: length, trim, uppercase, split, join, replace, contains and the rest.

A string’s characters are grapheme clusters: what a reader sees as one character, however many code points or bytes encode it. String.length, String.slice, String.take, String.reverse and iteration all count that way, so String.length("héllo") is 5 and an emoji with a skin tone counts as 1.

The search functions (starts_with, ends_with, replace, split, find, find_all) take any Matcher: a String, a Regex or a Codepoint. contains takes the same three as String’s Contains impls.

Import with import std::strings.

A String matches its own text, a Regex (std::regex) matches its pattern, and a Codepoint matches itself, so String.split("a,b", ",") and String.split(text, Regex`\s+`) are the same function. The thing to look for is called a matcher, not a pattern, because a pattern in Nomi is a destructuring shape.

  • Each Matcher function returns one of these operations with the matcher first (is_contained_in, is_prefix_of, is_suffix_of, split_in, replace_in, find_all_in, find_in). A type of your own implements it to become searchable, and a function of your own takes any matcher as a Matcher parameter.
  • String.contains is String’s Contains impl at the same three types, chosen by the needle’s type, so a String also satisfies where C: Contains<String>.
  • String.replace replaces every match. With a Regex it expands group references in the replacement ($1, ${name}, $$ for a $); with any other matcher the replacement is literal text.
  • String.captures and String.captures_all take a Regex rather than any Matcher, since only a regex has groups, and return each match’s groups as the regex’s capture type (capture types).
  • String.split and the other Matcher search functions are generic, so a call with a String or a Regex runs as that type’s search directly, and naming one as a value needs a function type to settle M: split: (String, String) -> List<String> = String.split.

String implements Iter<String>, one grapheme cluster per step, so every Iter owner function works on a string. To map or filter graphemes, run the generic adapter and join the result back into a String: Iter.map(s, f) |> String.join(), Iter.filter(s, p) |> String.join(). String.join takes any Iter<String> (a List, Set or Vector, graphemes, or a lazy chain) and a separator that defaults to "". String.reverse and String.length are String’s own functions and work by grapheme cluster too.

type String

Text, stored as UTF-8. A string is immutable: every function here returns a new string.

impl Contains<String> for String

fn contains(c: String, x: String) -> Bool

impl Contains.contains

True if x occurs in c as a substring. Every string holds "".

assert String.contains("hello world", "world")
refute String.contains("hello", "xyz")
assert String.contains("hello", "")

impl Contains<Regex<C>> for String

fn contains(c: String, x: Regex<C>) -> Bool

impl Contains.contains

True if x matches anywhere in c.

import std::regex.Regex

assert String.contains("order 66", Regex`\d+`)
refute String.contains("room", Regex`\d+`)

impl Contains<Codepoint> for String

fn contains(c: String, x: Codepoint) -> Bool

impl Contains.contains

True if x occurs in c.

assert String.contains("a-b", '-')
refute String.contains("ab", '-')
fn starts_with<M>(s: String, prefix: M) -> Bool where M: Matcher

type function on String

True if prefix matches at the start of s. prefix is a String, a Regex or a Codepoint. Every string starts with "".

import std::regex.Regex

assert String.starts_with("hello", "he")
assert String.starts_with("42 apples", Regex`\d+`)
refute String.starts_with("apples 42", Regex`\d+`)
fn ends_with<M>(s: String, suffix: M) -> Bool where M: Matcher

type function on String

True if suffix matches at the end of s. suffix is a String, a Regex or a Codepoint.

import std::regex.Regex

assert String.ends_with("hello.txt", ".txt")
assert String.ends_with("report.PDF", Regex`(?i)\.pdf`)
fn uppercase(s: String) -> String

type function on String

s in upper case. It maps each letter by Unicode’s rules, the same in every language, and keeps the number of letters: ß stays ß. String.uppercase_in applies a language’s rules.

assert String.uppercase("hello") == "HELLO"
assert String.uppercase("café") == "CAFÉ"
fn lowercase(s: String) -> String

type function on String

s in lower case. It maps each letter by Unicode’s rules, the same in every language. String.lowercase_in applies a language’s rules.

assert String.lowercase("Hello") == "hello"
assert String.lowercase("CAFÉ") == "café"
fn is_upper(s: String) -> Bool

type function on String

Whether s is in upper case: it has at least one cased letter, and every cased letter is upper case, as Codepoint.is_upper decides it. Characters with no case, such as digits and punctuation, count neither way. This is Python’s str.isupper.

refute String.is_upper("1, 2, 3")
assert String.is_upper("ÜMLÄÜTS!")
assert String.is_upper("WHAT'S UP?")
refute String.is_upper("Hello")
fn is_lower(s: String) -> Bool

type function on String

Whether s is in lower case: it has at least one cased letter, and every cased letter is lower case, as Codepoint.is_lower decides it. Characters with no case count neither way. This is Python’s str.islower.

refute String.is_lower("1, 2, 3")
assert String.is_lower("ümläüts!")
assert String.is_lower("what's up?")
refute String.is_lower("Hello")
fn capitalize(s: String) -> String

type function on String

Capitalizes s: its first grapheme in title case and the rest lowercased, as Python’s str.capitalize does. Title case is not upper case for a few letters that stand for two: dž becomes Dž, and ß becomes Ss. It uses Unicode’s full case mappings with no language’s rules; String.capitalize_in applies a language’s.

assert String.capitalize("hello WORLD") == "Hello world"
assert String.capitalize("džemal") == "Džemal"
assert String.capitalize("ÉCOLE") == "École"
assert String.capitalize("") == ""
fn uppercase_in(s: String, locale: Locale) -> String

type function on String

Upper-cases s as a reader of locale writes it, with Unicode’s full case mappings (SpecialCasing) and the rules of the locale’s language. Turkish and Azeri upper-case i to İ; Lithuanian drops the dot it keeps above an accented i. Every language upper-cases ß to SS. String.uppercase stays independent of any language.

assert String.uppercase_in("istanbul", Locale"tr") == "İSTANBUL"
assert String.uppercase_in("istanbul", Locale"en") == "ISTANBUL"
assert String.uppercase_in("Straße", Locale"de") == "STRASSE"
fn lowercase_in(s: String, locale: Locale) -> String

type function on String

Lower-cases s as a reader of locale writes it, with Unicode’s full case mappings (SpecialCasing) and the rules of the locale’s language. Turkish and Azeri lower-case I to dotless ı and İ to i; Lithuanian keeps the dot of an i under an accent (Í is i̇́). In every language a capital sigma that ends a word becomes ς. String.lowercase stays independent of any language.

assert String.lowercase_in("DİYARBAKIR", Locale"tr") == "diyarbakır"
assert String.lowercase_in("DIYARBAKIR", Locale"en") == "diyarbakir"
assert String.lowercase_in("ΟΔΟΣ", Locale"el") == "οδος"
fn capitalize_in(s: String, locale: Locale) -> String

type function on String

Capitalizes s as a reader of locale writes it: its first grapheme in title case and the rest lowercased, with the language’s rules of String.uppercase_in and String.lowercase_in. In Turkish and Azeri i becomes İ and I stays I. Title case differs from upper case for the letters that stand for two, as in String.capitalize: dž becomes Dž, and ß becomes Ss.

assert String.capitalize_in("istanbul", Locale"tr") == "İstanbul"
assert String.capitalize_in("IRMAK", Locale"tr") == "Irmak"
assert String.capitalize_in("istanbul", Locale"en") == "Istanbul"
assert String.capitalize_in("ßa", Locale"de") == "Ssa"
fn fold_case(s: String) -> String

type function on String

Folds case for caseless matching: two strings that differ only in case fold to the same string, in every language (Unicode’s full case folding). It is for comparing, not for showing: ß folds to ss. To sort without regard to case, use a Collator of secondary strength.

assert String.fold_case("Straße") == String.fold_case("STRASSE")
assert String.fold_case("ΣΑΣ") == "σασ"
fn snake_case(s: String) -> String

type function on String

s’s words in lower case joined by _: user_id from userId. Words split at _, - and whitespace, which are dropped (a run of them is one break, and those at either end are dropped too); where a lower-case letter or a digit is followed by an upper-case one (userId, v2Api); and at the end of an acronym, before the last of a run of capitals that a lower-case letter follows (HTTPServer). A digit stays with the word before it. Letters are upper or lower case by Unicode, and nothing is transliterated. String.kebab_case, String.pascal_case and String.camel_case split words the same way.

assert String.snake_case("userId") == "user_id"
assert String.snake_case("HTTPServer") == "http_server"
assert String.snake_case("parseHTTP2Request") == "parse_http2_request"
assert String.snake_case("v2Api") == "v2_api"
assert String.snake_case("--Hello   World--") == "hello_world"
assert String.snake_case("ÉcoleNormale") == "école_normale"
assert String.snake_case("") == ""
fn kebab_case(s: String) -> String

type function on String

s’s words in lower case joined by -, split as String.snake_case splits them.

assert String.kebab_case("userId") == "user-id"
assert String.kebab_case("HTTP_Server") == "http-server"
assert String.kebab_case("  big  red dog ") == "big-red-dog"
fn pascal_case(s: String) -> String

type function on String

s’s words joined with nothing between them, each capitalized as String.capitalize does (its first letter in upper (title) case and the rest in lower case), split as String.snake_case splits them. An acronym is not kept in capitals: HTTPServer becomes HttpServer.

assert String.pascal_case("extra_large") == "ExtraLarge"
assert String.pascal_case("in-transit") == "InTransit"
assert String.pascal_case("HTTPServer") == "HttpServer"
assert String.pascal_case("parseHTTP2Request") == "ParseHttp2Request"
assert String.pascal_case("école normale") == "ÉcoleNormale"
fn camel_case(s: String) -> String

type function on String

String.pascal_case with the first word in lower case.

assert String.camel_case("user_id") == "userId"
assert String.camel_case("HTTPServer") == "httpServer"
assert String.camel_case("v2 api") == "v2Api"
fn replace<M>(s: String, old: M, new: String) -> String where M: Matcher

type function on String

Replaces every non-overlapping match of old with new. old is any Matcher. With a Regex, new expands the match’s groups as Go’s regexp does: $1 or ${1} is group 1, ${name} a named group, $0 the whole match and $$ a literal $; a reference to no group is empty. With any other matcher, new is literal text.

import std::regex.Regex

assert String.replace("a.b.c", ".", "-") == "a-b-c"
assert String.replace("call 555-0100", Regex`\d`, "#") == "call ###-####"
assert String.replace("ann@home", Regex`(\w+)@(\w+)`, "$2:$1") == "home:ann"
assert String.replace("2026-10", Regex`(?P<y>\d+)-(?P<m>\d+)`, `${m}/${y}`) == "10/2026"
assert String.replace("5 apples", Regex`(\d+)`, "$$$1") == "$5 apples"
assert String.replace("a  b   c", Regex`\s+`, " ") == "a b c"
assert String.replace("pay $1", "$1", "$2") == "pay $2"
fn repeat(s: String, count: NonNegativeInt) -> String

type function on String

Concatenates count copies of s. The count is a NonNegativeInt: a literal is checked when the program is compiled, and a computed count goes through NonNegativeInt.try_from. A result of more than 2 GiB stops the program with a message naming the count.

assert String.repeat("ab", 3) == "ababab"
assert String.repeat("ab", 0) == ""
fn reverse(s: String) -> String

type function on String

s with its characters in the opposite order. It reverses by grapheme cluster, so a letter keeps its combining marks and an emoji made of several code points stays whole.

assert String.reverse("abc") == "cba"
assert String.reverse("👋🏽!") == "!👋🏽"
fn normalize(s: String, form: NormalForm) -> String

type function on String

Returns s in the given Unicode normalization form. Two strings that look the same and differ in form are not == until both are normalized to one form.

composed = "é"
decomposed = "é"
refute composed == decomposed
assert String.normalize(decomposed, NormalForm.NFC) == composed
assert String.normalize(composed, NormalForm.NFD) == decomposed
fn slice(s: String, start: Int, stop: Int) -> String

type function on String

The part of s from index start up to, and not including, index stop. Indexes count grapheme clusters from 0, the units String.length counts. A start below zero is 0, a stop past the end is the end, and a stop at or before start gives "".

assert String.slice("hello", 1, 4) == "ell"
assert String.slice("hello", 3, 99) == "lo"
assert String.slice("hello", -2, 3) == "hel"
assert String.slice("hello", 4, 2) == ""
fn take(s: String, n: Int) -> String

type function on String

The first n grapheme clusters of s, counted as String.slice and String.length count them. An n past the end gives the whole string, and an n of zero or less gives "". String.drop gives the rest, so String.take(s, n) + String.drop(s, n) == s.

assert String.take("hello", 2) == "he"
assert String.take("héllo", 2) == "hé"
assert String.take("hi", 5) == "hi"
assert String.take("hi", -1) == ""
fn drop(s: String, n: Int) -> String

type function on String

s after its first n grapheme clusters, counted as String.slice and String.length count them. An n past the end gives "", and an n of zero or less gives the whole string. String.take gives the clusters this drops.

assert String.drop("hello", 2) == "llo"
assert String.drop("héllo", 2) == "llo"
assert String.drop("hi", 5) == ""
assert String.drop("hi", -1) == "hi"
fn pad_start(s: String, width: Int, fill: String = " ") -> String

type function on String

Prepends copies of fill until s is width grapheme clusters long, the units String.length counts. A multi-character fill repeats and is cut to fit exactly. A string already width long or longer comes back unchanged, never truncated, and so does any s when fill is empty or width is zero or negative. The “é” below is “e” followed by U+0301 COMBINING ACUTE ACCENT: two code points, one grapheme cluster.

assert String.pad_start("5", 3) == "  5"
assert String.pad_start("5", 3, "0") == "005"
assert String.pad_start("5", 4, "ab") == "aba5"
assert String.pad_start("é", 3) == "  é"
assert String.pad_start("👋🏽", 2, "-") == "-👋🏽"
assert String.pad_start("hello", 3) == "hello"
assert String.pad_start("hi", 0) == "hi"
assert String.pad_start("hi", -4) == "hi"
assert String.pad_start("hi", 5, "") == "hi"

// Right-align a column of amounts.
assert String.pad_start("9.50", 7) == "   9.50"
assert String.pad_start("120.00", 7) == " 120.00"
fn pad_end(s: String, width: Int, fill: String = " ") -> String

type function on String

Appends copies of fill until s is width grapheme clusters long, the units String.length counts. A multi-character fill repeats and is cut to fit exactly. A string already width long or longer comes back unchanged, never truncated, and so does any s when fill is empty or width is zero or negative. The “é” in “café” below is “e” followed by U+0301 COMBINING ACUTE ACCENT, one grapheme cluster.

assert String.pad_end("ab", 4) == "ab  "
assert String.pad_end("5", 4, "ab") == "5aba"
assert String.pad_end("café", 6, ".") == "café.."
assert String.pad_end("👋🏽", 3, "*") == "👋🏽**"
assert String.pad_end("hello", 2) == "hello"
assert String.pad_end("hi", -1, "*") == "hi"
assert String.pad_end("hi", 5, "") == "hi"

// A table row: the name left-aligned, the count right-aligned.
row = String.pad_end("fig", 8) + String.pad_start("12", 4)
assert row == "fig       12"
assert String.length(row) == 12
fn join(parts: Iter<String>, separator: String = "") -> String

type function on String

Joins the strings of any Iter<String> (a List, Set or Vector, a String’s graphemes, or a lazy adapter chain) with separator between each element and nowhere else. The source is driven once, with no intermediate List. The separator defaults to "", so String.join(parts) concatenates.

assert String.join(["a", "b", "c"], ", ") == "a, b, c"
assert String.join([], ", ") == ""
assert String.join(["he", "llo"]) == "hello"
assert "héllo" |> Iter.map(String.uppercase) |> String.join() == "HÉLLO"
assert 1..=3 |> Iter.map(Int.to_string) |> String.join("-") == "1-2-3"
assert Vector["x", "y"] |> String.join("+") == "x+y"
assert Set["solo"] |> String.join(", ") == "solo"
fn join_list(items: List<String>, locale: Locale, style: ListStyle = ListStyle.And, width: ListWidth = ListWidth.Wide) -> String

type function on String

Joins items into one phrase as a reader of locale lists things, with CLDR’s list patterns: style says what the list means (And, Or, or Unit for the parts of one measure, such as “3 feet, 2 inches”) and width picks the pattern’s wide, short or narrow words. The last two items join by the pattern’s end form, each earlier one by its middle form and the first by its start form, so en writes a, b, and c and a and b. Materialize an Iter with Iter.to_list() first.

assert String.join_list(["a", "b", "c"], Locale"en") == "a, b, and c"
assert String.join_list(["a", "b"], Locale"en") == "a and b"

assert [1000, 2000]
|> Iter.map(&Int.format(&1, Locale"de"))
|> Iter.to_list()
|> String.join_list(Locale"de") == "1.000 und 2.000"

assert String.join_list(["a", "b", "c"], Locale"en-GB") == "a, b and c"
assert String.join_list(["a", "b"], Locale"en", ListStyle.Or) == "a or b"
assert String.join_list(["a", "b", "c"], Locale"en", ListStyle.And, ListWidth.Short) == "a, b, & c"
assert String.join_list(["a", "b", "c"], Locale"pl") == "a, b i c"
assert String.join_list(["a", "b", "c"], Locale"ja") == "a、b、c"

assert String.join_list(["3 quarters", "1 dime"], Locale"en", ListStyle.Unit)
    == "3 quarters, 1 dime"

items: List<String> = []
assert String.join_list(items, Locale"en") == ""
fn split<M>(s: String, separator: M) -> List<String> where M: Matcher

type function on String

Splits s into the list of pieces between the matches of separator, a String, a Regex or a Codepoint. The separators are not in the result. Two matches side by side, or one at either end, leave an empty string between them, and a string with no match comes back as the one piece, so String.split("", ",") is [""]. An empty separator splits s into its code points. String.join with the same separator puts the pieces back together.

import std::regex.Regex

assert String.split("a,b,c", ",") == ["a", "b", "c"]
assert String.split("a, b, c", ", ") == ["a", "b", "c"]
assert String.split(",a,", ",") == ["", "a", ""]
assert String.split("abc", "-") == ["abc"]
assert String.split("hello", "") == ["h", "e", "l", "l", "o"]
assert String.split("a, b,c", Regex`,\s*`) == ["a", "b", "c"]
assert "one  two\tthree" |> String.split(Regex`\s+`) == ["one", "two", "three"]

// Named as a value, a generic search function needs its type.
split: (String, String) -> List<String> = String.split
assert split("a,b", ",") == ["a", "b"]
fn find_all<M>(s: String, needle: M) -> List<String> where M: Matcher

type function on String

Every non-overlapping match of needle in s, left to right. With a String needle each match is the needle itself, so the list’s length is the number of occurrences.

import std::regex.Regex

assert String.find_all("order 66, aisle 7", Regex`\d+`) == ["66", "7"]
assert String.find_all("banana", "an") == ["an", "an"]
assert String.find_all("banana", "x") == []
fn find<M>(s: String, needle: M) -> Maybe<String> where M: Matcher

type function on String

The first match of needle in s, the leftmost, or None when there is none. It is the first element find_all would return. With a String needle the match is the needle itself, and an empty needle matches at the start of any text; an empty regex match is Some("").

import std::regex.Regex

assert String.find("order 66, aisle 7", Regex`\d+`) == Some("66")
assert String.find("banana", "an") == Some("an")
assert String.find("banana", "x") == None
assert String.find("none", Regex`\d+`) == None
fn captures<C>(s: String, re: Regex<C>) -> Maybe<C>

type function on String

The capture groups of the first match of re in s, the leftmost, or None when there is none, as the C of re’s type Regex<C> shapes them. The groups are the pattern’s from group 1, in the order it opens them: the whole match is not one, and String.find gives it. A Regex literal’s C has one part per group, String for a group every match fills and Maybe<String> for one a match can leave out, such as either side of (a)|(b): a tuple of them, an anonymous struct when every group is named, the one part alone for a single unnamed group, and Unit when there is none. A regex compiled while the program runs is a Regex<List<Maybe<String>>>, whose groups are a list.

import std::regex.Regex

assert String.captures("ann@home", Regex`(\w+)@(\w+)`) == Some(("ann", "home"))
assert String.captures("b", Regex"(a)|(b)") == Some((None, Some("b")))
assert String.captures("v12", Regex`v(\d+)`) == Some("12")
date = Regex`(?P<year>\d{4})-(?P<month>\d\d)?`
assert String.captures("2024-", date) == Some({year: "2024", month: None})
assert String.captures("no address", Regex`(\w+)@(\w+)`) == None
assert String.captures("a1", Regex.compile("(\\w)(\\d)")?) == Some([Some("a"), Some("1")])
fn captures_all<C>(s: String, re: Regex<C>) -> List<C>

type function on String

The capture groups of every non-overlapping match of re in s, left to right, each as String.captures gives them; [] when nothing matches. The matches are the ones String.find_all returns.

import std::regex.Regex

pairs = String.captures_all("a=1, b=22", Regex`(\w)=(\d+)`)
assert pairs == [("a", "1"), ("b", "22")]
assert String.captures_all("none", Regex`(\d)`) == []
fn words(s: String) -> List<String>

type function on String

The words of s: the pieces between runs of Unicode whitespace, which includes U+00A0 NO-BREAK SPACE and U+3000. Unlike split, leading, trailing and repeated whitespace never produce empty strings.

assert String.words("  1   2\t3 \n") == ["1", "2", "3"]
assert String.words("") == []
assert String.words("   ") == []
assert String.words("café 🙂ok") == ["café", "🙂ok"]
assert String.words("a\u{a0}b\u{3000}c") == ["a", "b", "c"]
fn lines(s: String) -> List<String>

type function on String

The lines of s, split on \n or \r\n with the terminator removed. Unlike split(s, "\n"), a final terminator does not add an empty last line; a lone \r is not a terminator.

assert String.lines("a\nb\r\nc\n") == ["a", "b", "c"]
assert String.lines("a\n\nb") == ["a", "", "b"]
assert String.lines("") == []
assert String.lines("\n") == [""]
assert String.lines("a\rb") == ["a\rb"]
assert String.lines("é\n🙂") == ["é", "🙂"]
fn trim(s: String) -> String

type function on String

s without the whitespace at its start and end. Whitespace is Unicode’s: spaces, tabs, newlines, carriage returns, and others such as U+00A0 NO-BREAK SPACE. Whitespace inside the text stays.

assert String.trim("  hello  ") == "hello"
assert String.trim("\n\tworld\n") == "world"
assert String.trim("a  b") == "a  b"
fn to_int(s: String) -> Maybe<Int>

type function on String

Parses s as a base-10 integer: digits with an optional + or - in front, and whitespace allowed around them. Returns Some(n), or None for anything else: empty text, a letter, a ., a _ separator. An Int has no largest value, so no number of digits is too many.

assert String.to_int("42") == Some(42)
assert String.to_int("-7") == Some(-7)
assert String.to_int("  3  ") == Some(3)
assert String.to_int("abc") == None
assert String.to_int("4.0") == None
assert String.to_int("") == None
fn to_float(s: String) -> Maybe<Float>

type function on String

Parses s as a base-10 Float, the same in every locale: an optional sign, digits, an optional . with digits on both sides, and an optional exponent (e or E, an optional sign, digits). Surrounding whitespace is tolerated, as String.to_int tolerates it. Returns None for anything else: empty text, _ separators, hex, .5 or 5., the words Inf and NaN, and a value too large for a Float. The result is the Float nearest the text. To read what a reader of some locale wrote (1.234,5), use Float.parse_in.

assert String.to_float("19.99") == Some(19.99)
assert String.to_float("-2.5e3") == Some(-2500.0)
assert String.to_float(" 7 ") == Some(7.0)
assert String.to_float("1,5") == None
assert String.to_float(".5") == None
assert String.to_float("1e400") == None
fn to_decimal(s: String) -> Maybe<Decimal>

type function on String

Parses s as a plain base-10 Decimal. It accepts an optional sign, _ digit separators and one fractional part, and the number of digits after the . becomes the scale ("1.50" is scale 2). Exponent notation is not accepted, and neither is whitespace around the number; String.trim it first. Returns None for empty or malformed input.

assert String.to_decimal("1.50") == Some(1.50d)
assert String.to_decimal("1_000") == Some(1000d)
assert String.to_decimal(" 1.50") == None
assert String.to_decimal("oops") == None
fn to_bytes(s: String) -> Bytes

type function on String

The bytes of s’s UTF-8 encoding.

assert String.to_bytes("ab")
|> Bytes.to_list()
|> Iter.map(Byte.to_int)
|> Iter.to_list() == [97, 98]
fn to_codepoints(s: String) -> List<Codepoint>

type function on String

The Unicode code points of s, in order. A character a reader sees as one can be several: “e” followed by U+0301 is two.

assert "ab"
    |> String.to_codepoints()
    |> Iter.map(Codepoint.to_int)
    |> Iter.to_list()
    |> List.equal([97, 98])
fn from_codepoints(cps: List<Codepoint>) -> String

type function on String

The string of the codepoints in cps, in order: the inverse of String.to_codepoints. It takes a List, as to_codepoints gives one; end a lazy chain of codepoints with Iter.to_list().

assert String.from_codepoints(['h', 'i']) == "hi"
assert String.from_codepoints([]) == ""
assert "héllo" |> String.to_codepoints() |> String.from_codepoints() == "héllo"

shifted =
    "abc"
    |> String.to_codepoints()
    |> Iter.map(&Int.to_codepoint(Codepoint.to_int(&1) + 1))
    |> Maybe.values()
    |> Iter.to_list()
    |> String.from_codepoints()

assert shifted == "bcd"
fn to_literal(s: String) -> String

type function on String

s as a Nomi string literal that reads back as s: quoted, with \n, \r, \t, \\ and \" escaped, \u{...} for any other character that is not printable (NUL is \u{0}, a no-break space \u{a0}), and ${ written \${, so nothing in it interpolates. Letters, combining marks and emoji are written as they are. So are the invisible characters that are part of something visible: an emoji’s zero-width joiners, variation selectors and tags ("👩‍💻"), and a zero-width joiner or non-joiner between two non-ASCII letters or marks, as in a Devanagari conjunct or a Persian word. One anywhere else (a\u{200d}b, at either end, beside a space) is escaped. What a program that writes Nomi source, such as a code generator, writes a string with, and a String’s Debug.

In detail:

  • A newline, tab or other control character shows as its escape rather than raw: dbg "a\nb" prints "a\nb" on one line. A carriage return is \r, and NUL is \u{0}, since Nomi has no \0 escape.
  • A $ or { alone, non-ASCII letters, combining marks and emoji are written as they are, an emoji’s zero-width joiners, variation selectors and tags included ("👩‍💻", not "👩\u{200d}💻").
  • A zero-width joiner or non-joiner between two non-ASCII letters or combining marks is part of the word and is written as it is too: a Devanagari conjunct ("क्‍ष", a joiner after a virama) or a Persian word ("می‌خواهم").
  • Any other zero-width joiner, non-joiner or variation selector ("a\u{200d}b", one at either end of the string, beside a space or punctuation, or doubled), and a no-break space (\u{a0}, \u{202f}), are escaped, so an invisible character stays visible.

nomi fmt writes string literals by the same rule. The same literal is what a String reads as inside a container’s Debug, an assertion’s values: row and the debugger’s variable view.

assert String.to_literal("a\tb") == "\"a\\tb\""
assert String.to_literal("say \"hi\"") == "\"say \\\"hi\\\"\""
assert String.to_literal("\${x} costs $5") == "\"\\\${x} costs $5\""
assert String.to_literal("\r") == "\"\\r\""
assert String.to_literal("a\u{0}b") == "\"a\\u{0}b\""
assert String.to_literal("a\u{200d}b") == "\"a\\u{200d}b\""
assert String.to_literal("x\u{202f}y") == "\"x\\u{202f}y\""
assert String.to_literal("$5 {x}") == "\"$5 {x}\""
fn to_typed_literal(s: String, tag: String) -> String

type function on String

A typed literal with prefix tag and fixed text s, as a program writes it: in double quotes when s needs no escape there, in backticks when it does and holds no backtick or line break, and otherwise as String.to_literal quotes it (style rule 21). A type’s Debug shows its value this way.

assert String.to_typed_literal("EUR", "Currency") == "Currency\"EUR\""
assert String.to_typed_literal("\\d+", "Regex") == "Regex`\\d+`"
assert String.to_typed_literal("say \"hi\"", "Regex") == "Regex`say \"hi\"`"
assert String.to_typed_literal("a`b\\d", "Regex") == "Regex\"a`b\\\\d\""
fn strip_prefix(s: String, prefix: String) -> Maybe<String>

type function on String

s without prefix at its start: Some(rest) when s starts with prefix, and None when it does not.

assert String.strip_prefix("hello world", "hello ") == Some("world")
assert String.strip_prefix("hello", "xyz") == None
fn strip_suffix(s: String, suffix: String) -> Maybe<String>

type function on String

s without suffix at its end: Some(rest) when s ends with suffix, and None when it does not.

assert String.strip_suffix("hello.txt", ".txt") == Some("hello")
assert String.strip_suffix("hello", "xyz") == None
fn length(s: String) -> NonNegativeInt

type function on String

The number of characters in s, counted as grapheme clusters: what a reader sees as one character. An accented letter is one, whether it is stored as one code point or as a letter and a combining mark, and so is an emoji built from several code points. It does not count bytes or code points: String.to_bytes and String.to_codepoints give those. Iter.count(s) gives the same number; this scans the text without building each cluster.

assert String.length("hello") == 5
assert String.length("héllo") == 5
assert String.length("é") == 1
assert String.length("👋🏽") == 1
assert List.length(String.to_codepoints("👋🏽")) == 2
assert String.length("") == 0

impl Matcher for String

fn is_contained_in(needle: String, text: String) -> Bool

impl Matcher.is_contained_in

True if needle occurs in text.

impl Matcher for String

fn is_prefix_of(prefix: String, text: String) -> Bool

impl Matcher.is_prefix_of

True if text begins with prefix.

impl Matcher for String

fn is_suffix_of(suffix: String, text: String) -> Bool

impl Matcher.is_suffix_of

True if text ends with suffix.

impl Matcher for String

fn split_in(separator: String, text: String) -> List<String>

impl Matcher.split_in

Splits on every occurrence; an empty separator splits at every codepoint.

impl Matcher for String

fn replace_in(old: String, text: String, replacement: String) -> String

impl Matcher.replace_in

Replaces every non-overlapping occurrence.

impl Matcher for String

fn find_all_in(needle: String, text: String) -> List<String>

impl Matcher.find_all_in

One copy of needle per non-overlapping occurrence.

impl Matcher for String

fn find_in(needle: String, text: String) -> Maybe<String>

impl Matcher.find_in

needle itself when it occurs in text.

impl Iter for String

fn each_while(s: String, yield: (String) -> Bool) -> Bool

impl Iter.each_while

A String iterates by grapheme cluster, one per user-visible character: Iter.to_list("héllo") is ["h", "é", "l", "l", "o"]. Pushes each cluster to yield, stopping when it returns False.

impl Display for String

fn to_string(s: String) -> String

impl Display.to_string

The raw text, with no quotes, so "hello ${name}" does not double-quote name. Debug gives the round-trippable literal instead (String.to_literal), so io.inspect("a\"b") reveals the escape. String is the one primitive where the two differ.

assert Display.to_string("a\"b") == "a\"b"
assert Debug.inspect("a\"b") == "\"a\\\"b\""

impl Add<String, String> for String

fn add(lhs: String, rhs: String) -> String

impl Add.add

impl Summable for String

fn empty_sum() -> String

impl Summable.empty_sum

The sum of no Strings: "". Summing Strings concatenates them in order; to put a separator between them, use String.join.

assert String.empty_sum() == ""
assert "ab" + String.empty_sum() == "ab"
assert Iter.sum(["no", "m", "i"]) == "nomi"

impl Debug for String

fn inspect(s: String) -> String

impl Debug.inspect

The string as a Nomi literal that reads back as it: String.to_literal.

assert String.inspect("a\nb\tc") == "\"a\\nb\\tc\""
assert Debug.inspect(["x\ny"]) == "[\"x\\ny\"]"

impl Equatable for String

fn equal(a: String, b: String) -> Bool

impl Equatable.equal

impl Hashable for String

fn hash(s: String) -> Int

impl Hashable.hash

The FNV-1a 64-bit hash of the UTF-8 bytes, as an Int. It is not cryptographic.

impl Comparable for String

fn compare(a: String, b: String) -> Ordering

impl Comparable.compare

subtype NonEmptyString String when fn s -> s != ""

A String with at least one character: a name, a key, a label. A literal is checked when the program is compiled, so "" where a NonEmptyString is expected is an error before the program runs; NonEmptyString.try_from(s) checks a String computed at run time. It is in the prelude.

subtype: NonEmptyString is a subtype of String. A literal where a NonEmptyString is expected is checked when the program is compiled; NonEmptyString.try_from(...) checks a value when it runs.

name: NonEmptyString = "Ada"
assert String.length(name) == 3
assert NonEmptyString.try_from(String.trim("  ")) == None
assert NonEmptyString.try_from(String.trim(" x ")) == Some("x")
fn try_from(value: String) -> Maybe<NonEmptyString>

type function on NonEmptyString

Some of the value when it satisfies NonEmptyString’s rules, None when it does not.

enum ListStyle
    And
    Or
    Unit
end

What a list String.join_list writes means: CLDR’s list pattern types.

Variants

  • And

    All of the items: “a, b, and c”.

  • Or

    One of the items: “a, b, or c”.

  • Unit

    The parts of one measure: “3 feet, 2 inches”.

impl Debug for ListStyle

fn inspect(value: ListStyle) -> String

impl Debug.inspect

impl Equatable for ListStyle

fn equal(a: ListStyle, b: ListStyle) -> Bool

impl Equatable.equal

enum ListWidth
    Wide
    Short
    Narrow
end

How short the words String.join_list writes between items are. English writes “and” wide and ”&” short; many locales write the same at every width.

impl Debug for ListWidth

fn inspect(value: ListWidth) -> String

impl Debug.inspect

impl Equatable for ListWidth

fn equal(a: ListWidth, b: ListWidth) -> Bool

impl Equatable.equal

enum NormalForm
    NFC
    NFD
    NFKC
    NFKD
end

Unicode normalization forms (UAX #15). Equality and hashing compare bytes, so two strings that look the same in different forms are not ==: a precomposed “é” (U+00E9) differs from a decomposed “e” followed by U+0301. Normalize both to one form before comparing text from mixed sources.

impl Debug for NormalForm

fn inspect(value: NormalForm) -> String

impl Debug.inspect

impl Display for NormalForm

fn to_string(value: NormalForm) -> String

impl Display.to_string