Skip to content

String.graphemes โ€‹

ant
func String.graphemes(s: string): Array[string]

String.graphemes returns the extended grapheme clusters of s (Unicode UAX #29), the units a reader sees as characters.

Details โ€‹

  • Splits s into the units a reader sees as one character (UAX #29 extended grapheme clusters). Joining the elements gives s back.
  • One grapheme can be several code points: a letter with combining accents, a flag, an emoji with a skin tone. String.chars splits these apart.
  • An empty s gives [].
  • It does not normalize: "\u{E9}" and "e\u{301}" are each one grapheme, and still different strings.

Basic examples โ€‹

Split a word into its characters:

ant
String.graphemes("ant") // ["a", "n", "t"]

A flag is one grapheme, though it is two code points:

ant
String.graphemes("๐Ÿ‡จ๐Ÿ‡ญ!") // ["๐Ÿ‡จ๐Ÿ‡ญ", "!"]
"๐Ÿ‡จ๐Ÿ‡ญ!".chars()           // ["๐Ÿ‡จ", "๐Ÿ‡ญ", "!"]

Count what a reader sees with len:

ant
len(String.graphemes("๐Ÿ‘๐Ÿฝ")) // 1
"๐Ÿ‘๐Ÿฝ".length()               // 2

Scope โ€‹

An empty string gives an empty array:

ant
"".graphemes() // []

A combining accent stays with the letter before it:

ant
len("e\u{301}a".graphemes())   // 2
len("noe\u{308}l".graphemes()) // 4

An accent at the very start has no letter to attach to, so it is a grapheme of its own:

ant
len("\u{301}a".graphemes()) // 2

A family emoji is three people and two zero width joiners, five code points in one grapheme:

ant
let family = "๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง"
family.length()         // 5
len(family.graphemes()) // 1

Two flags in a row pair up their regional indicators, and a lone indicator left over is a grapheme of its own:

ant
"๐Ÿ‡จ๐Ÿ‡ญ๐Ÿ‡ฉ๐Ÿ‡ช".graphemes() // ["๐Ÿ‡จ๐Ÿ‡ญ", "๐Ÿ‡ฉ๐Ÿ‡ช"]
"๐Ÿ‡จ๐Ÿ‡ญ๐Ÿ‡ฉ".graphemes()  // ["๐Ÿ‡จ๐Ÿ‡ญ", "๐Ÿ‡ฉ"]

A Windows line break, "\r\n", is one grapheme:

ant
"a\r\nb".graphemes() // ["a", "\r\n", "b"]

Three Hangul jamo combine into one syllable, and a Devanagari conjunct holds together:

ant
len("\u{1100}\u{1161}\u{11A8}".graphemes()) // 1
len("เคจเคฎเคธเฅเคคเฅ‡".graphemes())                      // 3

Call it through . on a string, or put the string first in a pipe:

ant
"x\u{303}y".graphemes().map({ x.length() }) // [2, 1]
"Zoรซ" | String.graphemes()                  // ["Z", "o", "รซ"]

The parameter is named s:

ant
String.graphemes(s: "ok") // ["o", "k"]

As a function value, it splits each element of an array:

ant
["hi", "๐Ÿœ๐Ÿœ"].map(String.graphemes) // [["h", "i"], ["๐Ÿœ", "๐Ÿœ"]]

Applications โ€‹

Reverse text without moving an accent onto another letter or splitting a flag. Reversing the code points instead breaks both:

ant
func reverse(s: string): string {
  s.graphemes().reverse() | String.concat()
}

println(reverse("noe\u{308}l ๐Ÿ‡จ๐Ÿ‡ญ"))
println("noe\u{308}l ๐Ÿ‡จ๐Ÿ‡ญ".chars().reverse() | String.concat())
text
๐Ÿ‡จ๐Ÿ‡ญ leฬˆon
๐Ÿ‡ญ๐Ÿ‡จ lฬˆeon

Shorten text to a number of characters for display, never cutting one in half:

ant
func truncate(s: string, n: int): string {
  let gs = s.graphemes()
  if len(gs) <= n {
    return s
  }
  String.concat(gs.slice(0, n)) + "โ€ฆ"
}

println(truncate("Ant ๐Ÿœ language", 5))
println(truncate("๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง", 2))
text
Ant ๐Ÿœโ€ฆ
๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€ฆ

Take the initials of a name, keeping each one whole:

ant
func initials(name: string): string {
  name.fields().map({ x.graphemes()[0] }) | String.concat()
}

initials("E\u{301}mile Zola") // "EฬZ"

Properties and relations โ€‹

Joining the graphemes gives the string back, and every grapheme is a non-empty string:

ant
for s in ["", "ant", "noe\u{308}l", "๐Ÿ‡จ๐Ÿ‡ญ๐Ÿ‡ฉ", "๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง\r\n"] {
  let gs = s.graphemes()
  assert(String.concat(gs) == s)
  assert(gs.every({ !x.isEmpty() }))
}

A grapheme holds one code point or more, so there are never more graphemes than code points:

ant
for s in ["", "ant", "e\u{301}", "๐Ÿ‘๐Ÿฝ", "เคจเคฎเคธเฅเคคเฅ‡"] {
  assert(len(s.graphemes()) <= s.length())
}

For text with no combining marks, joiners, or flags, the graphemes are the code points:

ant
let s = "plain ASCII text"
assert(s.graphemes() == s.chars())

Possible issues โ€‹

String.length counts code points, not graphemes. Count graphemes with len of the result:

ant
"e\u{301}".length()         // 2
len("e\u{301}".graphemes()) // 1

A for loop over a string steps through its code points, not its graphemes. Loop over the graphemes to visit the characters a reader sees:

ant
let s = "e\u{301}"
var points = 0
for c in s {
  points += 1
}
var chars = 0
for g in s.graphemes() {
  chars += 1
}
assert(points == 2)
assert(chars == 1)

String.slice takes code point indices, so it can cut a grapheme in half. Here it keeps the first person and a joiner of the family:

ant
"๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง".slice(0, 2).length()    // 2
"๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง".graphemes()[0].length() // 5

String.graphemes does not normalize. The two spellings of "รฉ" are each one grapheme, but not the same string. Normalize first to compare them:

ant
"\u{E9}".graphemes() == "e\u{301}".graphemes() // false
"e\u{301}".normalize("NFC").graphemes()        // ["รฉ"]

See also โ€‹

String.chars ยท String.length ยท String.slice ยท String.normalize ยท String.concat ยท String.codePoint ยท String.toCodePoints ยท Array.reverse