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
stringis 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.charsgives the code points as an array to index,String.toCodePointsgives them as integers, andString.toBytesgives the bytes. - There is no character type. A character is a string of one code point, so the class tests such as
String.isDigittake a string.String.graphemessplits text into what a reader sees as characters. String.unicodeVersionnames 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)orString.fromInt(n, 16).padStart(8, "0")inside interpolation.
Basic examples
Clean up a value and test it:
let name = " Ada Lovelace "
String.trim(name) // "Ada Lovelace"
String.startsWith(name.trim(), "A") // true
String.length("ant") // 3Split a line into fields and join them back:
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:
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:
let n = 3
"${n} ants" // "3 ants"
"ant" + "hill" // "anthill"
String.from([1, 2]) // "[1, 2]"A raw string keeps backslashes and ${ as written:
`C:\temp\${x}` // "C:\\temp\\\${x}"A for loop visits each code point as a one-code-point string:
for c in "née" {
println(c)
}n
é
eText 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:
"日本語".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:
"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:
String.fromInt(255, 16).padStart(8, "0") // "000000ff"String.cut returns a String.Cut record, or null when the separator is absent:
"key=value".cut("=") // String.Cut{ before: "key", after: "value" }
"novalue".cut("=") // nullFunctions by job
Size and pieces
- String.length: the number of code points
- String.isEmpty: whether there are none
- String.slice: the code points from
fromup toto - String.chars: one string per code point
- String.graphemes: one string per character as a reader sees it
Searching
- String.contains: whether
toccurs ins - String.startsWith, String.endsWith: whether
sbegins or ends witht - String.indexOf, String.lastIndexOf: the first or last code point index of
t, ornull - String.count: how many times
toccurs, without overlap
Splitting and joining
- String.split: the pieces between each separator
- String.cut: the two sides of the first separator, as String.Cut
- String.fields: the runs between white space
- String.lines: the lines of a text
- String.join: pieces with a separator between them
- String.concat: pieces one after the other
- String.repeat:
ncopies of a string
Trimming and padding
- String.trim, String.trimStart, String.trimEnd: white space removed at both ends, the start, or the end
- String.trimPrefix, String.trimSuffix: a prefix or suffix removed once
- String.padStart, String.padEnd: padding up to a width
Replacing
- String.replace: every occurrence replaced
- String.replaceFirst: the first occurrence replaced
Case and normalization
- String.toUpper, String.toLower: upper or lower case, with Unicode's full mappings
- String.foldCase: a key in which case does not matter
- String.equalFold: whether two strings are equal without regard to case
- String.normalize: one of the four Unicode normalization forms
Character classes
- String.isDigit, String.isNumber: decimal digits, or any numbers
- String.isLetter, String.isUpper, String.isLower: letters, upper-case, or lower-case letters
- String.isSpace: white space
- String.isPunct, String.isSymbol, String.isMark: punctuation, symbols, or marks such as combining accents
- String.isControl, String.isGraphic, String.isPrint: control characters (Cc), graphic code points (L, M, N, P, S, Zs), or printable ones (L, M, N, P, S, and the space)
- String.category: the general category of one code point
- String.inScript: whether one code point belongs to a script
Code points and bytes
- String.codePoint, String.fromCodePoint: one code point to an
intand back - String.toCodePoints, String.fromCodePoints: every code point to an
intand back - String.toBytes: the UTF-8 bytes
- String.fromBytes: bytes as text, or
nullwhen they are not UTF-8 - String.fromBytesLossy: bytes as text, with U+FFFD for what is not UTF-8
Numbers and rendering
- String.toInt, String.toUint, String.toFloat: a number read from text, or
null - String.fromInt: an integer in a base
- String.fromFloat: a float with a fixed number of decimals
- String.from: any value, as
printlnand interpolation render it
Applications
Read key=value settings, skipping blank lines and lines without =:
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:
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:
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)hello-ant-worldProperties and relations
len and String.length agree, and a string is empty when its length is 0:
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:
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:
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:
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:
let s = "ant"
println(s[0]) // error: string cannot be indexedlet s = "ant"
s.slice(0, 1) // "a"
s.chars()[0] // "a"+ joins only two strings; a number goes in through interpolation or String.fromInt:
let n = 3
println("ants: " + n) // error: + needs both operands of one type, got string and intlet 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:
"\u{E9}" == "e\u{301}" // false
"\u{E9}".normalize("NFC") == "e\u{301}".normalize("NFC") // trueComparison is by code point, not by dictionary order, so every upper-case ASCII letter comes before every lower-case one:
"Zebra" < "apple" // true
"Zebra".foldCase() < "apple".foldCase() // falsejoin 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:
let parts = ["a", "b"]
println(parts.join(",")) // error: Array[string] has no field or function joinlet 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:
let s = "ab"
println(s.length) // error: string is not a record, so it has no field lengthlet s = "ab"
s.length() // 2
len(s) // 2String.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:
"STRASSE".toLower() == "Straße".toLower() // false
String.equalFold("STRASSE", "Straße") // trueA 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:
"🇨🇭".length() // 2
len("🇨🇭".graphemes()) // 1See also
String type, String literals, Raw strings, Bytes, Regex, String.Cut, len, Text
