Skip to content

String ​

String holds the functions of string, an immutable sequence of Unicode code points stored as UTF-8. Lengths, indices, and slices count code points, and a character is a string of one code point; String.graphemes gives what a reader sees as characters.

The String namespace holds the functions on strings. Each function that works on a string takes that string first, so String.trim(s), s.trim(), and s | String.trim() are the same call. A few take something else first and are called through the namespace or a pipe: String.join and String.concat take an array, and String.fromInt, String.fromCodePoint, and the other from functions build a string from another value.

Details ​

  • A string is immutable. No function changes a string; the ones that edit text return a new one.
  • Lengths, indices, and slices count code points. There is no s[i]: String.chars gives the code points as an array to index, String.toCodePoints gives them as integers, and String.toBytes gives the bytes.
  • There is no character type. A character is a string of one code point, so the class tests such as String.isDigit take a string. String.graphemes splits text into what a reader sees as characters.
  • String.unicodeVersion names the version of the Unicode tables that grapheme splitting, normalization, case mapping, and the class tests follow.
  • There is no format string: write String.fromFloat(x, 2) or String.fromInt(n, 16).padStart(8, "0") inside interpolation.

Basic examples ​

Clean up a value and test it:

ant
let name = "  Ada Lovelace "
String.trim(name)                   // "Ada Lovelace"
String.startsWith(name.trim(), "A") // true
String.length("ant")                // 3

Split a line into fields and join them back:

ant
let parts = String.split("red,green,blue", ",")
parts                     // ["red", "green", "blue"]
String.join(parts, " / ") // "red / green / blue"

Calls chain through ., or the string goes down a pipe:

ant
let raw = "  Hello, World  "
raw.trim().toLower()                                 // "hello, world"
raw | String.trim() | String.replace("World", "Ant") // "Hello, Ant"

Scope ​

Interpolation renders any value with String.from, and + joins two strings:

ant
let n = 3
"${n} ants"         // "3 ants"
"ant" + "hill"      // "anthill"
String.from([1, 2]) // "[1, 2]"

A raw string keeps backslashes and ${ as written:

ant
`C:\temp\${x}` // "C:\\temp\\\${x}"

A for loop visits each code point as a one-code-point string:

ant
for c in "née" {
  println(c)
}
text
n
é
e

Text outside ASCII counts by code point. An accent written as its own code point counts on its own, and String.graphemes keeps it with its letter:

ant
"日本語".length()       // 3
"e\u{301}".length()     // 2
"e\u{301}x".graphemes() // ["é", "x"]
"é".toCodePoints()      // [233]

Numbers go to and from text through dedicated functions. A string that is not a number reads as null:

ant
"42".toInt()                 // 42
"4 2".toInt()                // null
String.fromInt(255, 16)      // "ff"
String.fromFloat(3.14159, 2) // "3.14"

There is no format string; a zero-padded number is String.fromInt followed by padStart:

ant
String.fromInt(255, 16).padStart(8, "0") // "000000ff"

String.cut returns a String.Cut record, or null when the separator is absent:

ant
"key=value".cut("=") // String.Cut{ before: "key", after: "value" }
"novalue".cut("=")   // null

Functions by job ​

Size and pieces ​

Searching ​

Splitting and joining ​

Trimming and padding ​

Replacing ​

Case and normalization ​

Character classes ​

Code points and bytes ​

Numbers and rendering ​

Applications ​

Read key=value settings, skipping blank lines and lines without =:

ant
let text = "host=localhost\n\nport=8080\nverbose\n"
let settings: Map[string, string] = Map{}
for line in text.lines() {
  let kv = line.cut("=")
  if kv != null {
    settings[kv.before.trim()] = kv.after.trim()
  }
}
settings // Map{ "host": "localhost", "port": "8080" }

Format a table row with fixed-width columns:

ant
func row(name: string, qty: int): string {
  name.padEnd(8, ".") + String.fromInt(qty).padStart(4)
}
row("apples", 12) // "apples..  12"
row("figs", 300)  // "figs.... 300"

Build a slug from a title:

ant
let title = "  Hello, Ant World! "
let slug = title
  | String.toLower()
  | String.fields()
  | Array.map({ x.chars().filter({ x.isLetter() }) | String.concat() })
  | String.join("-")
println(slug)
text
hello-ant-world

Properties and relations ​

len and String.length agree, and a string is empty when its length is 0:

ant
let s = "anthill"
assert(len(s) == String.length(s))
assert(String.isEmpty(s) == (len(s) == 0))

Splitting and joining with the same separator gives the string back:

ant
let s = "a,b,,c"
assert(String.join(s.split(","), ",") == s)

The code points of a string, its characters, and its UTF-8 bytes all lead back to it:

ant
let s = "naïve 🐜"
assert(String.concat(s.chars()) == s)
assert(String.fromCodePoints(s.toCodePoints()) == s)
assert(String.fromBytes(s.toBytes()) == s)
assert(len(s.chars()) == len(s))

A call through ., a pipe, and a direct call are the same call:

ant
let s = " Ant "
assert(s.trim() == String.trim(s))
assert((s | String.trim()) == String.trim(s))

Possible issues ​

A string cannot be indexed. Take one code point with String.slice, or index the array of String.chars:

ant
let s = "ant"
println(s[0]) // error: string cannot be indexed
ant
let s = "ant"
s.slice(0, 1) // "a"
s.chars()[0]  // "a"

+ joins only two strings; a number goes in through interpolation or String.fromInt:

ant
let n = 3
println("ants: " + n) // error: + needs both operands of one type, got string and int
ant
let n = 3
"ants: ${n}"                 // "ants: 3"
"ants: " + String.fromInt(n) // "ants: 3"

== compares code points and does not normalize, so the two spellings of é differ until both go through String.normalize:

ant
"\u{E9}" == "e\u{301}"                                   // false
"\u{E9}".normalize("NFC") == "e\u{301}".normalize("NFC") // true

Comparison is by code point, not by dictionary order, so every upper-case ASCII letter comes before every lower-case one:

ant
"Zebra" < "apple"                       // true
"Zebra".foldCase() < "apple".foldCase() // false

join is a String function, not an Array one. A call through . on an array goes to the Array namespace, so parts.join(",") does not compile:

ant
let parts = ["a", "b"]
println(parts.join(",")) // error: Array[string] has no field or function join
ant
let parts = ["a", "b"]
String.join(parts, ",")  // "a,b"
parts | String.join(",") // "a,b"

s.length without parentheses reads a field, and a string has no fields. Call it, or use len:

ant
let s = "ab"
println(s.length) // error: string is not a record, so it has no field length
ant
let s = "ab"
s.length() // 2
len(s)     // 2

String.toLower applies the full case mappings and is not a key for comparing text without regard to case. Compare or key such text through String.foldCase or String.equalFold:

ant
"STRASSE".toLower() == "Straße".toLower() // false
String.equalFold("STRASSE", "Straße")     // true

A code point is not always a character a reader sees. String.length counts the code points of a flag, and String.graphemes counts the flag once:

ant
"🇨🇭".length()         // 2
len("🇨🇭".graphemes()) // 1

See also ​

String type, String literals, Raw strings, Bytes, Regex, String.Cut, len, Text