String.length
func String.length(s: string): intString.length returns the number of code points in s, not the graphemes a reader sees.
Details
- Counts code points, not bytes and not graphemes.
""has length0. - The length in bytes,
Bytes.length(String.toBytes(s)), can be larger. - What a reader sees as one character can be several code points; use
String.graphemesto count those.
Basic examples
Count the characters of a word:
String.length("ant") // 3
String.length("hello") // 5The empty string has length 0:
String.length("") // 0Scope
A letter outside ASCII, written as one code point, counts once:
String.length("héllo") // 5
String.length("日本語") // 3
String.length("🐜") // 1An escape such as \t or \n is one code point, and so is a line break inside a string literal that spans lines:
String.length("a\tb\n") // 4
String.length("ab
cd") // 5In a raw string, a backslash is a character of its own:
String.length(`a\nb`) // 4An accent written as a combining mark after its letter is a code point of its own:
String.length("\u{E9}") // 1
String.length("e\u{301}") // 2A flag is two regional indicator symbols, and a family emoji is three people joined by two zero-width joiners:
String.length("🇨🇭") // 2
String.length("👨👩👧") // 5
len(String.graphemes("👨👩👧")) // 1Call it through ., in a pipe, or pass it as a function value:
"ant".length() // 3
"ant" | String.length() // 3
["a", "bb", "ccc"].map(String.length) // [1, 2, 3]Applications
Check that a user name has between 3 and 16 characters:
func validName(name: string): bool {
let n = name.trim().length()
n >= 3 && n <= 16
}
validName("Ann") // true
validName(" Al ") // false
validName("") // falseShorten a title to a limit, ending it with an ellipsis when it was cut:
func shorten(s: string, limit: int): string {
if s.length() <= limit { return s }
s.slice(0, limit - 1) + "…"
}
shorten("Ant", 10) // "Ant"
shorten("An anthill of tunnels", 10) // "An anthil…"Find the longest word of a sentence:
"ants dig long tunnels".fields().maxBy(String.length) // "tunnels"Underline a heading with as many characters as it has:
let title = "Größe"
println(title)
println("=".repeat(title.length()))Größe
=====Sort words from the shortest to the longest:
["tunnel", "ant", "hill"] | Array.sortBy(String.length) // ["ant", "hill", "tunnel"]Properties and relations
len and String.length give the same count:
for s in ["", "ant", "héllo", "👨👩👧"] {
assert(len(s) == String.length(s))
}The length is the number of elements of String.chars and of String.toCodePoints:
let s = "e\u{301}🇨🇭 ant"
assert(s.chars().length() == s.length())
assert(s.toCodePoints().length() == s.length())The length of a concatenation is the sum of the lengths:
let a = "ant"
let b = "hill🐜"
assert((a + b).length() == a.length() + b.length())String.isEmpty is true exactly when the length is 0:
for s in ["", " ", "ant"] {
assert(s.isEmpty() == (s.length() == 0))
}String.slice from 0 to the length gives back the whole string:
let s = "anthill 🐜"
assert(s.slice(0, s.length()) == s)A string has at least as many bytes as code points, and as many only when it is all ASCII:
for s in ["ant", "héllo", "🐜"] {
assert(s.toBytes().length() >= s.length())
}
"ant".toBytes().length() // 3
"héllo".toBytes().length() // 6
"🐜".toBytes().length() // 4Possible issues
String.length counts code points, not graphemes, so a skin tone or an accent that is a mark of its own adds to the count. Count graphemes with len of String.graphemes:
String.length("👍🏽") // 2
len(String.graphemes("👍🏽")) // 1
String.length("cafe\u{301}") // 5
len(String.graphemes("cafe\u{301}")) // 4The two spellings of é have different lengths. String.normalize brings them to one:
String.length("e\u{301}") // 2
"e\u{301}".normalize("NFC").length() // 1The length is not the size in bytes. A limit on stored or sent bytes needs the byte count:
let s = "日本語"
s.length() // 3
s.toBytes().length() // 9Changing case can change the length, since String.toUpper uses the full mappings:
String.length("ß") // 1
"ß".toUpper().length() // 2A value of a named primitive type is not a string, so passing it is a compile error:
type Name = string
let n = Name("Ann")
println(String.length(n)) // error: cannot use Name where string is expectedConvert it with string(n), or use len, which unwraps it:
type Name = string
let n = Name("Ann")
println(string(n).length())
println(len(n))3
3See also
String.graphemes · String.chars · String.toCodePoints · String.isEmpty · String.slice · String.toBytes · String.normalize · Bytes.length · Array.length
