Skip to content

String.length ​

ant
func String.length(s: string): int

String.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 length 0.
  • 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.graphemes to count those.

Basic examples ​

Count the characters of a word:

ant
String.length("ant")   // 3
String.length("hello") // 5

The empty string has length 0:

ant
String.length("") // 0

Scope ​

A letter outside ASCII, written as one code point, counts once:

ant
String.length("héllo")  // 5
String.length("日本語") // 3
String.length("🐜")     // 1

An escape such as \t or \n is one code point, and so is a line break inside a string literal that spans lines:

ant
String.length("a\tb\n") // 4
String.length("ab
cd") // 5

In a raw string, a backslash is a character of its own:

ant
String.length(`a\nb`) // 4

An accent written as a combining mark after its letter is a code point of its own:

ant
String.length("\u{E9}")   // 1
String.length("e\u{301}") // 2

A flag is two regional indicator symbols, and a family emoji is three people joined by two zero-width joiners:

ant
String.length("🇨🇭")         // 2
String.length("👨‍👩‍👧")         // 5
len(String.graphemes("👨‍👩‍👧")) // 1

Call it through ., in a pipe, or pass it as a function value:

ant
"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:

ant
func validName(name: string): bool {
  let n = name.trim().length()
  n >= 3 && n <= 16
}

validName("Ann")   // true
validName("  Al ") // false
validName("")      // false

Shorten a title to a limit, ending it with an ellipsis when it was cut:

ant
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:

ant
"ants dig long tunnels".fields().maxBy(String.length) // "tunnels"

Underline a heading with as many characters as it has:

ant
let title = "Größe"
println(title)
println("=".repeat(title.length()))
text
Größe
=====

Sort words from the shortest to the longest:

ant
["tunnel", "ant", "hill"] | Array.sortBy(String.length) // ["ant", "hill", "tunnel"]

Properties and relations ​

len and String.length give the same count:

ant
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:

ant
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:

ant
let a = "ant"
let b = "hill🐜"
assert((a + b).length() == a.length() + b.length())

String.isEmpty is true exactly when the length is 0:

ant
for s in ["", " ", "ant"] {
  assert(s.isEmpty() == (s.length() == 0))
}

String.slice from 0 to the length gives back the whole string:

ant
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:

ant
for s in ["ant", "héllo", "🐜"] {
  assert(s.toBytes().length() >= s.length())
}
"ant".toBytes().length()   // 3
"héllo".toBytes().length() // 6
"🐜".toBytes().length()    // 4

Possible 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:

ant
String.length("👍🏽")                  // 2
len(String.graphemes("👍🏽"))          // 1
String.length("cafe\u{301}")         // 5
len(String.graphemes("cafe\u{301}")) // 4

The two spellings of é have different lengths. String.normalize brings them to one:

ant
String.length("e\u{301}")            // 2
"e\u{301}".normalize("NFC").length() // 1

The length is not the size in bytes. A limit on stored or sent bytes needs the byte count:

ant
let s = "日本語"
s.length()           // 3
s.toBytes().length() // 9

Changing case can change the length, since String.toUpper uses the full mappings:

ant
String.length("ß")     // 1
"ß".toUpper().length() // 2

A value of a named primitive type is not a string, so passing it is a compile error:

ant
type Name = string

let n = Name("Ann")
println(String.length(n)) // error: cannot use Name where string is expected

Convert it with string(n), or use len, which unwraps it:

ant
type Name = string

let n = Name("Ann")
println(string(n).length())
println(len(n))
text
3
3

See also ​

String.graphemes · String.chars · String.toCodePoints · String.isEmpty · String.slice · String.toBytes · String.normalize · Bytes.length · Array.length