string

Functions for working with immutable strings. Strings use "..." literal syntax with {expr} interpolation.

A character, on this page, is one Unicode code point. What a reader sees as one letter can be several: "e\u{301}", an e followed by a combining accent, is shown as é and has two. The emoji of a family of three is three people and two invisible joiners: five. string.length, string.chars, string.slice and every offset count code points, so a slice can cut an accent from its letter.

import string

fn main() {
  println(string.length("e\u{301}")) -- 2
  println(string.length("\u{e9}")) -- 1
  println(string.slice("e\u{301}x", 0, 1)) -- e
}
open in playground

Offsets and lengths count characters, not bytes. A string of ASCII text only (source code, logs, CSV) knows that each of its characters is one byte, so string.length, string.slice, string.split_at, string.starts_with_at and the index that string.index_of gives take no longer for an offset deep into the text than for one at its start. In text with other characters an offset is counted from the start of the string each time: a loop that takes such text one index at a time takes time that grows with the square of its length. Scan it with string.chars or string.split instead, which go through it once.

import list
import string

fn main() {
  -- One pass over the characters, for any text.
  let vowels = string.chars("naïve café")
    |> list.filter { c -> string.contains("aeiouïé", c) }
    |> list.length
  println(vowels) -- 5
}
open in playground

Summary

FunctionSignatureDescription
char_code(String) -> Option(Int)Unicode code point of the first character, or None for an empty string
chars(String) -> List(String)Split string into single-character strings
contains(String, String) -> BoolCheck if substring exists
ends_with(String, String) -> BoolCheck suffix
from(a) -> String where a: DisplayConvert any value to its display string
from_char_code(Int) -> Option(String)Character of a Unicode code point, or None if it is none
index_of(String, String) -> Option(Int)Character index of first occurrence
byte_length(String) -> IntLength in bytes
is_alnum(String) -> BoolAll chars are alphanumeric
is_alpha(String) -> BoolAll chars are alphabetic
is_digit(String) -> BoolAll chars are ASCII digits
is_empty(String) -> BoolString has zero length
is_lower(String) -> BoolAll chars are lowercase
is_upper(String) -> BoolAll chars are uppercase
is_whitespace(String) -> BoolAll chars are whitespace
join(List(String), String) -> StringJoin list with separator
last_index_of(String, String) -> Option(Int)Character index of last occurrence
left(a, Int) -> String where a: DisplayThe value as Display shows it, padded with spaces on the right to width
length(String) -> IntLength in characters
lines(String) -> List(String)Split on \n (strips trailing \r, no empty final element)
pad_left(String, Int, String) -> StringPad to width on the left
pad_right(String, Int, String) -> StringPad to width on the right
repeat(String, Int) -> StringRepeat string n times
replace(String, String, String) -> StringReplace all occurrences
right(a, Int) -> String where a: DisplayThe value as Display shows it, padded with spaces on the left to width
slice(String, Int, Int) -> StringSubstring by character indices
split(String, String) -> List(String)Split on separator
split_at(String, Int) -> Option((String, String))Split into two strings at a character index, or None past the end
split_once(String, String) -> Option((String, String))Split at the first separator into the text before and after it, or None if it is not there
starts_with(String, String) -> BoolCheck prefix
starts_with_at(String, Int, String) -> BoolCheck prefix at a given character offset
strip_prefix(String, String) -> Option(String)The rest after the prefix, or None if s does not start with it
strip_suffix(String, String) -> Option(String)The rest before the suffix, or None if s does not end with it
to_lower(String) -> StringConvert to lowercase
to_upper(String) -> StringConvert to uppercase
trim(String) -> StringRemove leading and trailing whitespace
trim_end(String) -> StringRemove trailing whitespace
trim_start(String) -> StringRemove leading whitespace

string.char_code

string.char_code(s: String) -> Option(Int)

Returns Some of the Unicode code point of the first character, or None for an empty string.

import string

fn main() {
  println(string.char_code("A")) -- Some(65)
  println(string.char_code("")) -- None
}
open in playground

string.chars

string.chars(s: String) -> List(String)

Splits the string into a list of single-character strings.

import string

fn main() {
  println(string.chars("hi")) -- ["h", "i"]
}
open in playground

string.contains

string.contains(s: String, sub: String) -> Bool

Returns true if sub appears anywhere in s.

import string

fn main() {
  println(string.contains("hello world", "world")) -- true
}
open in playground

string.ends_with

string.ends_with(s: String, suffix: String) -> Bool

Returns true if s ends with suffix.

import string

fn main() {
  println(string.ends_with("hello.silt", ".silt")) -- true
}
open in playground

string.from

string.from(x: a) -> String where a: Display

Converts any value to its display string representation. This is the programmatic equivalent of string interpolation "{value}".

import string

fn main() {
  println(string.from(42)) -- 42
  println(string.from(2.0)) -- 2.0
  println(string.from(true)) -- true
  println(string.from([1, 2, 3])) -- [1, 2, 3]
}
open in playground

string.from_char_code

string.from_char_code(code: Int) -> Option(String)

Returns Some of the single-character string of a Unicode code point, or None for a number that is none (a negative one, a surrogate, one above 0x10FFFF).

import string

fn main() {
  println(string.from_char_code(65)) -- Some("A")
  println(string.from_char_code(-1)) -- None
}
open in playground

string.index_of

string.index_of(s: String, needle: String) -> Option(Int)

Returns Some(index) with the character index of the first occurrence of needle in s, or None if not found.

import string

fn main() {
  println(string.index_of("hello", "ll")) -- Some(2)
  println(string.index_of("hello", "z")) -- None
}
open in playground

string.last_index_of

string.last_index_of(s: String, needle: String) -> Option(Int)

Returns Some(index) with the character index of the last occurrence of needle in s, or None if not found. Counterpart to string.index_of, using the same character-based indexing convention.

import string

fn main() {
  println(string.last_index_of("banana", "a")) -- Some(5)
  println(string.last_index_of("banana", "z")) -- None
}
open in playground

string.is_alnum

string.is_alnum(s: String) -> Bool

Returns true if all characters are alphanumeric. Returns false for empty strings.

import string

fn main() {
  println(string.is_alnum("abc123")) -- true
  println(string.is_alnum("abc!")) -- false
  println(string.is_alnum("")) -- false
}
open in playground

string.is_alpha

string.is_alpha(s: String) -> Bool

Returns true if all characters are alphabetic. Returns false for empty strings.

import string

fn main() {
  println(string.is_alpha("hello")) -- true
  println(string.is_alpha("abc123")) -- false
  println(string.is_alpha("")) -- false
}
open in playground

string.is_digit

string.is_digit(s: String) -> Bool

Returns true if all characters are ASCII digits (0-9). Returns false for empty strings.

import string

fn main() {
  println(string.is_digit("123")) -- true
  println(string.is_digit("12a")) -- false
  println(string.is_digit("")) -- false
}
open in playground

string.is_empty

string.is_empty(s: String) -> Bool

Returns true if the string has zero length.

import string

fn main() {
  println(string.is_empty("")) -- true
  println(string.is_empty("hi")) -- false
}
open in playground

string.is_lower

string.is_lower(s: String) -> Bool

Returns true if all characters are lowercase. Returns false for empty strings.

import string

fn main() {
  println(string.is_lower("hello")) -- true
  println(string.is_lower("Hello")) -- false
  println(string.is_lower("")) -- false
}
open in playground

string.is_upper

string.is_upper(s: String) -> Bool

Returns true if all characters are uppercase. Returns false for empty strings.

import string

fn main() {
  println(string.is_upper("HELLO")) -- true
  println(string.is_upper("Hello")) -- false
  println(string.is_upper("")) -- false
}
open in playground

string.is_whitespace

string.is_whitespace(s: String) -> Bool

Returns true if all characters are whitespace. Returns false for empty strings.

import string

fn main() {
  println(string.is_whitespace("  \t")) -- true
  println(string.is_whitespace(" a ")) -- false
  println(string.is_whitespace("")) -- false
}
open in playground

string.join

string.join(xs: List(String), sep: String) -> String

Joins a list of strings with a separator between each pair.

To build a long string from many parts, collect the parts in a list and join them once. Adding a part to a string at each step of a loop or a fold ("{acc}{part}") copies the text built so far each time, so the work grows with the square of the length.

import string

fn main() {
  let joined = string.join(["a", "b", "c"], ", ")
  println(joined) -- a, b, c
}
open in playground

string.byte_length

string.byte_length(s: String) -> Int

Returns the length of the string in bytes (UTF-8 encoding). See also string.length which counts characters.

import string

fn main() {
  println(string.byte_length("hello")) -- 5
  println(string.byte_length("café")) -- 5  (é is 2 bytes in UTF-8)
}
open in playground

string.left

string.left(x: a, width: Int) -> String where a: Display

Returns x as Display shows it (as in "{x}"), with spaces after it up to width characters: the text sits at the left of the column. Any value that has Display will do, so a number needs no conversion first. A text as wide as width or wider comes back as it is, as it does for a negative width. A width over 10,000,000 is a runtime error. For another pad character than a space, use string.pad_right.

import string

fn main() {
  println("[{string.left("name", 8)}]") -- [name    ]
  println("[{string.left(3.5, 6)}]") -- [3.5   ]
  println("[{string.left("toolong", 3)}]") -- [toolong]
}
open in playground

string.length

string.length(s: String) -> Int

Returns the number of characters in the string. Use string.byte_length if you need the size in bytes.

import string

fn main() {
  println(string.length("hello")) -- 5
  println(string.length("café")) -- 4  (4 characters, 5 bytes)
}
open in playground

string.lines

string.lines(s: String) -> List(String)

Splits s on \n newline characters. A trailing newline does not produce an empty final element, so "a\nb\n" yields ["a", "b"]. A trailing \r on each line is stripped, which normalises \r\n line endings from Windows sources.

import string

fn main() {
  println(string.lines("a\nb\nc")) -- ["a", "b", "c"]
  println(string.lines("a\nb\n")) -- ["a", "b"]
  println(string.lines("")) -- []
}
open in playground

Input containing \r\n sequences (Windows line endings) has the trailing \r on each line stripped automatically.

string.pad_left

string.pad_left(s: String, width: Int, pad: String) -> String

Pads s on the left with pad, which must be exactly one character, until it is width characters long. To pad with spaces, use string.right, which also takes any value that has Display. Returns s unchanged if already at or beyond width, as it is for a negative width. A pad of any other length and a width over 10,000,000 are runtime errors.

import string

fn main() {
  println(string.pad_left("42", 5, "0")) -- 00042
}
open in playground

string.pad_right

string.pad_right(s: String, width: Int, pad: String) -> String

Pads s on the right with pad, which must be exactly one character, until it is width characters long. To pad with spaces, use string.left, which also takes any value that has Display. Returns s unchanged if already at or beyond width, as it is for a negative width. A pad of any other length and a width over 10,000,000 are runtime errors.

import string

fn main() {
  println(string.pad_right("hi", 5, ".")) -- hi...
}
open in playground

string.repeat

string.repeat(s: String, n: Int) -> String

Returns the string repeated n times. A negative n counts as 0 and returns an empty string.

import string

fn main() {
  println(string.repeat("ab", 3)) -- ababab
}
open in playground

string.replace

string.replace(s: String, from: String, to: String) -> String

Replaces all occurrences of from with to.

import string

fn main() {
  println(string.replace("hello world", "world", "silt"))
  -- hello silt
}
open in playground

string.right

string.right(x: a, width: Int) -> String where a: Display

Returns x as Display shows it (as in "{x}"), with spaces before it up to width characters: the text sits at the right of the column, as numbers do in a table. Any value that has Display will do. A text as wide as width or wider comes back as it is, as it does for a negative width. A width over 10,000,000 is a runtime error. For another pad character than a space, use string.pad_left.

import list
import string

fn main() {
  println("[{string.right(42, 6)}]") -- [    42]
  let rows = [("apples", 12), ("kiwis", 1500)]
  list.each(rows) { (name, n) -> println("{string.left(name, 8)}{string.right(n, 6)}") }
}
open in playground

string.slice

string.slice(s: String, start: Int, end: Int) -> String

Returns the substring from character index start (inclusive) to end (exclusive). Both indices are cut to the string: a negative one counts as 0, one past the end as the end. Returns an empty string if start > end.

import string

fn main() {
  println(string.slice("hello", 1, 4)) -- ell
}
open in playground

string.split

string.split(s: String, separator: String) -> List(String)

Splits the string on every occurrence of separator. A separator at the start or the end of s, or two side by side, gives an empty piece there (string.split(",a,", ",") is ["", "a", ""]), and an empty s is one empty piece. An empty separator splits s into its characters, with no empty piece at either end: string.split("abc", "") is ["a", "b", "c"], and string.split("", "") is [].

import string

fn main() {
  let parts = string.split("a,b,c", ",")
  println(parts) -- ["a", "b", "c"]
}
open in playground

string.split_at

string.split_at(s: String, idx: Int) -> Option((String, String))

Splits s into Some((left, right)) at character index idx. idx == 0 yields ("", s) and idx == length(s) yields (s, ""). A negative index or one past the end of the string is None.

import string

fn main() {
  println(string.split_at("hello", 2)) -- Some(("he", "llo"))
  println(string.split_at("hello", 0)) -- Some(("", "hello"))
  println(string.split_at("hello", 5)) -- Some(("hello", ""))
  println(string.split_at("hello", 6)) -- None
}
open in playground

string.split_once

string.split_once(s: String, separator: String) -> Option((String, String))

Splits s at the first separator into Some((before, after)), the separator itself in neither; None if s does not contain it. Only the first separator splits: the rest stays in after. It is the way to read key=value and --name=value.

import string

fn main() {
  println(string.split_once("--top=5", "=")) -- Some(("--top", "5"))
  println(string.split_once("a = b = c", " = ")) -- Some(("a", "b = c"))
  println(string.split_once("verbose", "=")) -- None
}
open in playground

string.starts_with

string.starts_with(s: String, prefix: String) -> Bool

Returns true if s starts with prefix.

import string

fn main() {
  println(string.starts_with("hello", "hel")) -- true
}
open in playground

string.starts_with_at

string.starts_with_at(s: String, offset: Int, prefix: String) -> Bool

Returns true if prefix appears in s starting at character offset. The offset is a character index (matching string.index_of and string.slice). Out-of-range offsets (negative, or past the end of the string) return false rather than panicking.

import string

fn main() {
  println(string.starts_with_at("hello", 2, "ll")) -- true
  println(string.starts_with_at("hello", 2, "lx")) -- false
  println(string.starts_with_at("hello", -1, "h")) -- false
  println(string.starts_with_at("hello", 99, "")) -- false
}
open in playground

string.strip_prefix

string.strip_prefix(s: String, prefix: String) -> Option(String)

Returns Some of the rest of s after prefix, or None if s does not start with prefix.

import string

fn main() {
  println(string.strip_prefix("Bearer xyz", "Bearer ")) -- Some("xyz")
  println(string.strip_prefix("Basic xyz", "Bearer ")) -- None
}
open in playground

string.strip_suffix

string.strip_suffix(s: String, suffix: String) -> Option(String)

Returns Some of the rest of s before suffix, or None if s does not end with suffix.

import string

fn main() {
  println(string.strip_suffix("notes.txt", ".txt")) -- Some("notes")
  println(string.strip_suffix("notes.md", ".txt")) -- None
}
open in playground

string.to_lower

string.to_lower(s: String) -> String

Converts all characters to lowercase.

import string

fn main() {
  println(string.to_lower("HELLO")) -- hello
}
open in playground

string.to_upper

string.to_upper(s: String) -> String

Converts all characters to uppercase.

import string

fn main() {
  println(string.to_upper("hello")) -- HELLO
}
open in playground

string.trim

string.trim(s: String) -> String

Removes leading and trailing whitespace.

import string

fn main() {
  println(string.trim("  hello  ")) -- hello
}
open in playground

string.trim_end

string.trim_end(s: String) -> String

Removes trailing whitespace only.

import string

fn main() {
  println(string.trim_end("hello   ")) -- hello
}
open in playground

string.trim_start

string.trim_start(s: String) -> String

Removes leading whitespace only.

import string

fn main() {
  println(string.trim_start("   hello")) -- hello
}
open in playground