Conceptcore
Grapheme cluster
Also called grapheme, extended grapheme cluster, user-perceived character, text element, Character (Swift), UAX 29.
A grapheme cluster is what a user sees as one character, such as é, a flag or a family emoji. It can be many code points, and UAX 29 gives the rules that find its boundaries.
- Applies to
- core-languages
Idea
A user does not see code points. A user sees letters, accented letters, flags and emoji, and each one looks like one character. The Unicode Standard calls such a unit a user-perceived character. In code, the unit is a grapheme cluster: a sequence of one or more code points that forms one character on the screen. UAX 29 says that "A single Unicode code point is often, but not always the same as a basic unit of a writing system for a language"1. The text below has 8 grapheme clusters but 13 code points.
import unicodedata
ZWJ = "\u200d"
def is_extend(c):
# Extend: nonspacing and enclosing marks, and the emoji skin tone modifiers.
return unicodedata.category(c) in ("Mn", "Me") or 0x1F3FB <= ord(c) <= 0x1F3FF
def is_ri(c):
return 0x1F1E6 <= ord(c) <= 0x1F1FF
def graphemes(s):
# A small subset of the UAX 29 rules, enough for this text:
# no break before Extend or ZWJ (GB9), no break after ZWJ (a short form of GB11),
# and regional indicators join in pairs (GB12, GB13).
out = []
for c in s:
prev = out[-1][-1] if out else None
if prev is not None and (is_extend(c) or c == ZWJ or prev == ZWJ):
out[-1] += c
elif prev is not None and is_ri(c) and is_ri(prev) and len(out[-1]) == 1:
out[-1] += c
else:
out.append(c)
return out
t = "cafe\u0301 \U0001F1EB\U0001F1F7 \U0001F469\U0001F3FD\u200d\U0001F692"
print(t)
print("UTF-8 bytes:", len(t.encode("utf-8")))
print("UTF-16 units:", len(t.encode("utf-16-le")) // 2)
print("code points:", len(t))
g = graphemes(t)
print("graphemes:", len(g))
for x in g:
print(f"[{x}]", " ".join(f"U+{ord(c):04X}" for c in x))
café 🇫🇷 👩🏽🚒
UTF-8 bytes: 31
UTF-16 units: 18
code points: 13
graphemes: 8
[c] U+0063
[a] U+0061
[f] U+0066
[é] U+0065 U+0301
[ ] U+0020
[🇫🇷] U+1F1EB U+1F1F7
[ ] U+0020
[👩🏽🚒] U+1F469 U+1F3FD U+200D U+1F692
The letter é here is e and the combining accent U+0301. The flag is two regional indicator symbols, F and R. The firefighter emoji is four code points: a woman, a skin tone modifier, a zero width joiner (ZWJ) and a fire engine. So the same text has four sizes: 31 bytes in UTF-8, 18 code units in UTF-16, 13 code points and 8 grapheme clusters. The function graphemes uses only three of the rules, and it is a sketch. A real program uses the full rules from a library or the standard library.
How it works
Rules, not a table. No list of all grapheme clusters exists, because a cluster can be any base character with any number of marks after it. UAX 29 gives rules that decide, between each two code points, whether a boundary is there. Each code point has a Grapheme_Cluster_Break property, such as Extend, ZWJ, Regional_Indicator or Control. The class Extend is the code points with "Grapheme_Extend = Yes, or Emoji_Modifier=Yes"1, which includes the nonspacing marks and the skin tone modifiers. The rules then look at the classes on each side:
- GB9: "Do not break before extending characters or ZWJ."1 So
eand U+0301 stay together. - GB11: "Do not break within emoji modifier sequences or emoji zwj sequences."1 So a ZWJ joins two pictographs into one emoji.
- GB12 and GB13: "do not break between regional indicator (RI) symbols if there is an odd number of RI characters before the break point"1. So the indicators pair up into flags, two at a time.
- GB999: otherwise, break everywhere.
Other rules keep CR LF together, keep the jamo of a Hangul syllable together, and keep some Indic conjuncts together.
Legacy and extended clusters. UAX 29 defines two variants. A legacy grapheme cluster is a base and the marks after it. An extended grapheme cluster also includes "all spacing combining marks, such as the spacing (but dependent) vowel signs in Indic scripts"1. In the Tamil syllable நி, the vowel sign is a spacing mark, so the syllable is one extended cluster but two legacy clusters. UAX 29 says that "The extended rules are recommended, except where the legacy variant is required for a specific environment"1. Most libraries use extended clusters.
Where the boundaries matter. "Grapheme clusters can be treated as units, by default, for processes such as the formatting of drop caps, as well as the implementation of text selection, arrow key movement, forward deletion, and so forth"1. A text field that moves the cursor by code points puts it between e and its accent. A limit on the number of characters must count something, and a count of code points or code units does not match what the user sees. A program that cuts a string to fit a field must cut at a cluster boundary, or it can cut a flag into two letters.
Tailoring. The default rules are not right for every language. "The notion of user-perceived character is not always an unambiguous concept for a given writing system"1, and UAX 29 allows "tailored grapheme clusters for specific locales"1. Some libraries, such as ICU, accept a locale for this reason.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Library | |
| Java | Standard library | |
| C | Library | |
| C# | Standard library | |
| JavaScript | Standard library | |
| TypeScript | Standard library | TypeScript uses the JavaScript Intl.Segmenter, and its library types describe the segments. No example file exists. |
| Go | Library | |
| Rust | Library | |
| Kotlin | Standard library | On the JVM, Kotlin uses java.text.BreakIterator.getCharacterInstance and the regex \X of java.util.regex. No example file exists because kotlinc is not installed. |
| SQL | Absent | Standard SQL has no grapheme function. LENGTH and CHAR_LENGTH count the characters of the character set of the column. No example file exists. |
| Bash | Absent | Bash has no grapheme operation. ${#s} counts the characters of the locale, which are code points in a UTF-8 locale. No example file exists. |
| PowerShell | Standard library | PowerShell can use the .NET System.Globalization.StringInfo class, which counts text elements. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no string operations. The browser finds grapheme clusters when it draws and selects the text. |
| CSS | Does not apply | CSS has no string operations. The browser segments the text for line breaks and selection. |
| Regular expressions | Native | In Java and in the Python regex module, \X matches one extended grapheme cluster. A JavaScript RegExp has no \X. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | stdlib | unicodedata.iter_graphemes in Python 3.15; before that, \X in the third-party regex module |
| JavaScript | stdlib | Intl.Segmenter with granularity: "grapheme" |
| TypeScript | stdlib | the JavaScript Intl.Segmenter and its types |
| Java | stdlib | BreakIterator.getCharacterInstance(); \X and \b{g} in java.util.regex |
| Kotlin | stdlib | the Java BreakIterator on the JVM |
| C# | stdlib | StringInfo and TextElementEnumerator; text elements are grapheme clusters |
| Go | library | no standard package; github.com/rivo/uniseg |
| Rust | library | no standard API; the unicode-segmentation crate, graphemes(true) |
| C | library | no standard API; ICU ubrk_open with UBRK_CHARACTER |
| C++ | library | no standard API; ICU BreakIterator::createCharacterInstance |
| Bash | absent | ${#s} counts characters of the locale, which are code points in UTF-8 |
| PowerShell | stdlib | the .NET System.Globalization.StringInfo |
| SQL | absent | no standard function; string lengths count characters of the character set |
| Regex | native | \X in Java and the Python regex module; not in JavaScript RegExp |
| HTML | n/a | the browser segments the text of a document when it draws it |
| CSS | n/a | the browser segments text for line breaks and selection |
Swift is the language that makes grapheme clusters the default. "Every instance of Swift's Character type represents a single extended grapheme cluster"2, and "An extended grapheme cluster is a sequence of one or more Unicode scalars that (when combined) produce a single human-readable character"2. So count on a Swift string counts clusters, and the book warns that it "must iterate over the Unicode scalars in the entire string"2.
In JavaScript, "The Intl.Segmenter object enables locale-sensitive text segmentation, enabling you to get meaningful items (graphemes, words or sentences) from a string"3. In Java, the default character BreakIterator "conforms to the Unicode Consortium's Extended Grapheme Cluster breaks"4, and in a regex, \X matches "Any Unicode extended grapheme cluster"5. In .NET, a cluster has another name: "The equivalent term in .NET is text element"6. Python 3.15 added unicodedata.iter_graphemes, which "uses extended grapheme cluster rules defined by Unicode Standard Annex #29"7. For earlier versions, the regex module supports \X, and "It conforms to the Unicode specification"8. The Rust standard library leaves the work to a crate, because "Getting grapheme clusters from strings, as with the Devanagari script, is complex, so this functionality is not provided by the standard library"9. The crate unicode-segmentation gives "Iterators which split strings on Grapheme Cluster, Word, or Sentence boundaries, according to the Unicode Standard Annex #29 rules"10. In Go, the package uniseg "provides tools to iterate over these grapheme clusters"11. In C and C++, the ICU character iterator "locates the boundaries according to the rules defined in" UAX 2912.
The example files show each mechanism on the same text. Python shows the code points of one emoji, NFC that joins e and its accent but cannot join a flag, a cut that loses the accent, and the Tamil spacing mark. JavaScript counts 8 segments with Intl.Segmenter, finds the segment that holds an index, and cuts by segments. Java uses BreakIterator and \X. C# uses StringInfo, ParseCombiningCharacters and the text element enumerator. Go, Rust, C and C++ have no standard API, so their examples use the same small rule subset as the Idea block, and their comments name the library that a real program uses. Go cuts at a byte limit and backs up to a cluster boundary, and Rust shows that a reverse by code points moves an accent onto the wrong letter.
import unicodedata
# The names of the code points in one emoji grapheme.
for c in "\U0001F469\U0001F3FD\u200d\U0001F692":
print(f"U+{ord(c):04X} {unicodedata.name(c)}")
# NFC can join "e" and U+0301 into one code point, but most graphemes have no such form.
e = "e\u0301"
print(len(e), len(unicodedata.normalize("NFC", e)))
flag = "\U0001F1EB\U0001F1F7"
print(len(flag), len(unicodedata.normalize("NFC", flag)))
# A cut by code points can split a grapheme. Here the accent is lost.
word = "cafe\u0301"
print(word[:4], len(word[:4]))
# A Tamil syllable: the vowel sign is a spacing mark, so it is a separate code point.
ni = "\u0BA8\u0BBF"
print(ni, len(ni), [unicodedata.category(c) for c in ni])
U+1F469 WOMAN
U+1F3FD EMOJI MODIFIER FITZPATRICK TYPE-4
U+200D ZERO WIDTH JOINER
U+1F692 FIRE ENGINE
2 1
2 2
cafe 4
நி 2 ['Lo', 'Mc']
- Verdict: stdlib. The firefighter emoji is four code points, and
unicodedata.namenames each one. NFC joinseand U+0301 into one code point, but a flag stays two code points. A cut of 4 code points loses the accent. The Tamil syllable is a letter and a spacing mark (Mc), so it is one extended cluster but two code points. Python 3.15 addsunicodedata.iter_graphemes, and the example does not use it, so it runs on older versions too.
#include <cstdint>
#include <cstdio>
#include <string>
#include <string_view>
#include <vector>
// The C++ standard library has no grapheme API. A real program uses ICU
// (icu::BreakIterator::createCharacterInstance). This sketch applies a small
// subset of the UAX 29 rules, with hand-written ranges for this text.
static char32_t decode(std::string_view s, std::size_t i, std::size_t& len) {
auto b = [&](std::size_t k) { return static_cast<char32_t>(static_cast<unsigned char>(s[i + k])); };
if (b(0) < 0x80) { len = 1; return b(0); }
if (b(0) < 0xE0) { len = 2; return ((b(0) & 0x1F) << 6) | (b(1) & 0x3F); }
if (b(0) < 0xF0) { len = 3; return ((b(0) & 0x0F) << 12) | ((b(1) & 0x3F) << 6) | (b(2) & 0x3F); }
len = 4;
return ((b(0) & 0x07) << 18) | ((b(1) & 0x3F) << 12) | ((b(2) & 0x3F) << 6) | (b(3) & 0x3F);
}
static bool is_extend(char32_t c) {
return (c >= 0x300 && c <= 0x36F) || (c >= 0x1F3FB && c <= 0x1F3FF) || c == 0xFE0F;
}
static bool is_ri(char32_t c) { return c >= 0x1F1E6 && c <= 0x1F1FF; }
static std::vector<std::string_view> graphemes(std::string_view s) {
std::vector<std::string_view> out;
std::size_t start = 0;
char32_t prev = 0;
int ri_run = 0;
for (std::size_t i = 0, len = 0; i < s.size(); i += len) {
char32_t c = decode(s, i, len);
bool join = i > 0 && (is_extend(c) || c == 0x200D || prev == 0x200D || (is_ri(c) && ri_run % 2 == 1));
if (!join && i > 0) {
out.push_back(s.substr(start, i - start));
start = i;
}
ri_run = is_ri(c) ? ri_run + 1 : 0;
prev = c;
}
if (!s.empty()) out.push_back(s.substr(start));
return out;
}
int main() {
std::string t = "cafe\u0301 \U0001F1EB\U0001F1F7 \U0001F469\U0001F3FD\u200D\U0001F692";
auto g = graphemes(t);
std::printf("%zu bytes, %zu graphemes\n", t.size(), g.size());
// Truncate to at most 22 bytes. A plain resize cuts the emoji.
std::string cut = t.substr(0, 22);
std::size_t keep = 0;
for (auto x : g) {
if (keep + x.size() > 22) break;
keep += x.size();
}
std::printf("%zu %02X %zu\n", cut.size(), static_cast<unsigned char>(cut.back()), keep);
// The last grapheme is one emoji of 15 bytes.
std::printf("%zu %s\n", g.back().size(), std::string(g.back()).c_str());
}
31 bytes, 8 graphemes
22 9F 16
15 👩🏽🚒
- Verdict: library. The C++ standard library has no grapheme API, so this sketch returns
std::string_viewpieces of the text. A real program uses ICU.substr(0, 22)ends with the byte9F, inside the skin tone modifier, and a cut at cluster boundaries keeps 16 bytes. The last cluster is the emoji, 15 bytes.
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String t = "cafe\u0301 " + Character.toString(0x1F1EB) + Character.toString(0x1F1F7)
+ " " + Character.toString(0x1F469) + Character.toString(0x1F3FD) + "\u200D"
+ Character.toString(0x1F692);
// length() counts UTF-16 code units, and codePoints() counts code points.
System.out.println(t.length() + " " + t.codePoints().count());
// A character BreakIterator finds extended grapheme cluster boundaries.
BreakIterator it = BreakIterator.getCharacterInstance();
it.setText(t);
List<Integer> starts = new ArrayList<>();
for (int b = it.first(); b != BreakIterator.DONE; b = it.next()) {
starts.add(b);
}
System.out.println((starts.size() - 1) + " " + starts);
// The regex \X matches one extended grapheme cluster.
Matcher m = Pattern.compile("\\X").matcher(t);
int n = 0;
String last = "";
while (m.find()) {
n++;
last = m.group();
}
System.out.println(n + " " + last.length() + " " + last.codePointCount(0, last.length()));
}
}
18 13
8 [0, 1, 2, 3, 5, 6, 10, 11, 18]
8 7 4
- Verdict: stdlib.
length()is 18 andcodePoints().count()is 13. The characterBreakIteratorgives 9 boundaries, so 8 clusters, and they arecharindexes. The regex\Xfinds the same 8 clusters, and the last one is 7charvalues and 4 code points.
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* The C library has no grapheme API. A real program uses ICU (ubrk_open
with UBRK_CHARACTER). This sketch decodes UTF-8 and applies a small
subset of the UAX 29 rules, with hand-written ranges for this text. */
static uint32_t decode(const unsigned char *s, size_t *len) {
if (s[0] < 0x80) { *len = 1; return s[0]; }
if (s[0] < 0xE0) { *len = 2; return ((s[0] & 0x1Fu) << 6) | (s[1] & 0x3Fu); }
if (s[0] < 0xF0) { *len = 3; return ((s[0] & 0x0Fu) << 12) | ((s[1] & 0x3Fu) << 6) | (s[2] & 0x3Fu); }
*len = 4;
return ((s[0] & 0x07u) << 18) | ((s[1] & 0x3Fu) << 12) | ((s[2] & 0x3Fu) << 6) | (s[3] & 0x3Fu);
}
static int is_extend(uint32_t c) {
return (c >= 0x300 && c <= 0x36F) || (c >= 0x1F3FB && c <= 0x1F3FF) || c == 0xFE0F;
}
static int is_ri(uint32_t c) { return c >= 0x1F1E6 && c <= 0x1F1FF; }
int main(void) {
const char *t = "cafe\u0301 \U0001F1EB\U0001F1F7 \U0001F469\U0001F3FD\u200D\U0001F692";
const unsigned char *s = (const unsigned char *)t;
size_t n = strlen(t), cps = 0, count = 0, start = 0;
uint32_t prev = 0;
int ri_run = 0;
printf("graphemes (start byte, length):");
for (size_t i = 0; i < n;) {
size_t len;
uint32_t c = decode(s + i, &len);
int join = i > 0 && (is_extend(c) || c == 0x200D || prev == 0x200D || (is_ri(c) && ri_run % 2 == 1));
if (!join) {
if (i > 0) printf(" %zu,%zu", start, i - start);
start = i;
count++;
}
ri_run = is_ri(c) ? ri_run + 1 : 0;
prev = c;
cps++;
i += len;
}
printf(" %zu,%zu\n", start, n - start);
printf("%zu bytes, %zu code points, %zu graphemes\n", n, cps, count);
return 0;
}
graphemes (start byte, length): 0,1 1,1 2,1 3,3 6,1 7,8 15,1 16,15
31 bytes, 13 code points, 8 graphemes
- Verdict: library. C has no grapheme API, so this sketch decodes UTF-8 by hand and applies a small subset of the rules. A real program uses ICU. The output gives the start byte and the length of each cluster: the accented
eis 3 bytes, the flag 8 and the emoji 15.
using System.Globalization;
using System.Text;
string t = "cafe\u0301 \U0001F1EB\U0001F1F7 \U0001F469\U0001F3FD\u200D\U0001F692";
// Length counts UTF-16 code units, and EnumerateRunes counts scalar values.
Console.WriteLine($"{t.Length} {t.EnumerateRunes().Count()}");
// StringInfo counts text elements, which are extended grapheme clusters.
var info = new StringInfo(t);
Console.WriteLine(info.LengthInTextElements);
// ParseCombiningCharacters gives the index where each text element starts.
Console.WriteLine(string.Join(" ", StringInfo.ParseCombiningCharacters(t)));
// The enumerator gives each text element as a string.
var e = StringInfo.GetTextElementEnumerator(t);
var sb = new StringBuilder();
while (e.MoveNext())
{
sb.Append(((string)e.Current).Length).Append(' ');
}
Console.WriteLine(sb.ToString().TrimEnd());
// SubstringByTextElements cuts by graphemes, so the accent stays.
Console.WriteLine(info.SubstringByTextElements(0, 4) == "cafe\u0301");
18 13
8
0 1 2 3 5 6 10 11
1 1 1 2 1 4 1 7
True
- Verdict: stdlib.
Lengthis 18 and the text has 13 runes.StringInfocounts 8 text elements.ParseCombiningCharactersgives thecharindex where each element starts, and the enumerator gives each element, so the lengths are 1, 2, 4 and 7charvalues.SubstringByTextElements(0, 4)keeps the accent.
const t = "cafe\u0301 \u{1F1EB}\u{1F1F7} \u{1F469}\u{1F3FD}\u200d\u{1F692}";
// length counts UTF-16 code units, and the spread counts code points.
console.log(t.length, [...t].length);
// Intl.Segmenter with granularity "grapheme" finds the user-perceived characters.
const seg = new Intl.Segmenter("en", { granularity: "grapheme" });
const parts = [...seg.segment(t)];
console.log(parts.length);
console.log(parts.map((p) => `${p.index}:${[...p.segment].length}`).join(" "));
// containing(i) finds the grapheme that holds code unit i.
const g = seg.segment(t).containing(12);
console.log(g.index, g.segment === "\u{1F469}\u{1F3FD}\u200d\u{1F692}");
// Cut to the first 4 graphemes, not to the first 4 code units.
console.log(parts.slice(0, 4).map((p) => p.segment).join(""), t.slice(0, 4));
18 13
8
0:1 1:1 2:1 3:2 5:1 6:2 10:1 11:4
11 true
café cafe
- Verdict: stdlib. The text is 18 code units and 13 code points.
Intl.Segmenterwithgranularity: "grapheme"finds 8 segments, and each segment has anindexin code units.containing(12)finds the emoji that starts at index 11. A cut to 4 segments keepsé, andslice(0, 4)loses the accent.
package main
import (
"fmt"
"strings"
"unicode"
"unicode/utf8"
)
const zwj = '\u200d'
// isExtend covers nonspacing and enclosing marks and the emoji skin tone modifiers.
func isExtend(r rune) bool {
return unicode.In(r, unicode.Mn, unicode.Me) || (r >= 0x1F3FB && r <= 0x1F3FF)
}
// graphemes applies a small subset of the UAX 29 rules: no break before
// Extend or ZWJ, no break after ZWJ, and regional indicators in pairs.
// A real program uses a library such as github.com/rivo/uniseg.
func graphemes(s string) []string {
var out []string
var prev rune = -1
riRun := 0
for _, r := range s {
ri := unicode.Is(unicode.Regional_Indicator, r)
join := prev >= 0 && (isExtend(r) || r == zwj || prev == zwj)
if prev >= 0 && ri && riRun%2 == 1 {
join = true
}
if join {
out[len(out)-1] += string(r)
} else {
out = append(out, string(r))
}
if ri {
riRun++
} else {
riRun = 0
}
prev = r
}
return out
}
func main() {
t := "cafe\u0301 \U0001F1EB\U0001F1F7 \U0001F469\U0001F3FD\u200d\U0001F692"
// len counts bytes, and RuneCountInString counts code points.
fmt.Println(len(t), utf8.RuneCountInString(t))
g := graphemes(t)
fmt.Println(len(g))
sizes := make([]string, len(g))
for i, x := range g {
sizes[i] = fmt.Sprint(len(x))
}
fmt.Println(strings.Join(sizes, " "))
// A cut at a byte limit can end inside the emoji. Cut at a grapheme boundary instead.
limit, n := 22, 0
for _, x := range g {
if n+len(x) > limit {
break
}
n += len(x)
}
fmt.Printf("%v %d %q\n", utf8.ValidString(t[:limit]), n, t[:n])
}
31 13
8
1 1 1 3 1 8 1 15
false 16 "café 🇫🇷 "
- Verdict: library. Go has no grapheme package in its standard library, so this sketch uses
unicode.Mn,unicode.Meandunicode.Regional_Indicatorwith a small subset of the rules. A real program usesgithub.com/rivo/uniseg. The accentedetakes 3 bytes, the flag 8 and the emoji 15. A cut at byte 22 is not valid UTF-8, so the code keeps only whole clusters and stops at byte 16.
// The standard library has no grapheme API. A real program uses the
// unicode-segmentation crate. This sketch applies a small subset of the
// UAX 29 rules, with hand-written ranges that are enough for this text.
fn is_extend(c: char) -> bool {
matches!(c, '\u{0300}'..='\u{036F}' | '\u{1F3FB}'..='\u{1F3FF}' | '\u{FE0F}')
}
fn is_ri(c: char) -> bool {
('\u{1F1E6}'..='\u{1F1FF}').contains(&c)
}
fn graphemes(s: &str) -> Vec<&str> {
let mut out: Vec<&str> = Vec::new();
let mut start = 0;
let mut prev: Option<char> = None;
let mut ri_run = 0;
for (i, c) in s.char_indices() {
let join = match prev {
None => false,
Some(p) => is_extend(c) || c == '\u{200D}' || p == '\u{200D}' || (is_ri(c) && ri_run % 2 == 1),
};
if !join && i > 0 {
out.push(&s[start..i]);
start = i;
}
ri_run = if is_ri(c) { ri_run + 1 } else { 0 };
prev = Some(c);
}
if !s.is_empty() {
out.push(&s[start..]);
}
out
}
fn main() {
let t = "cafe\u{0301} \u{1F1EB}\u{1F1F7} \u{1F469}\u{1F3FD}\u{200D}\u{1F692}";
// len counts bytes, and chars().count() counts code points.
println!("{} {}", t.len(), t.chars().count());
let g = graphemes(t);
println!("{}", g.len());
// Each grapheme is a &str slice that borrows from t.
let sizes: Vec<String> = g.iter().map(|x| x.len().to_string()).collect();
println!("{}", sizes.join(" "));
// chars().rev() reverses code points, so the accent moves onto the "!".
let bad: String = "cafe\u{0301}!".chars().rev().collect();
let good: String = graphemes("cafe\u{0301}!").into_iter().rev().collect();
println!("{:?} {:?}", bad, good);
}
31 13
8
1 1 1 3 1 8 1 15
"!\u{301}efac" "!e\u{301}fac"
- Verdict: library. The standard library has no grapheme API, so this sketch uses hand-written ranges. A real program uses the
unicode-segmentationcrate. Each cluster is a&strslice of the text.chars().rev()puts U+0301 after the!, so the accent moves to the wrong character. A reverse by clusters keepseand its accent together.
Variations and related ideas
- Normalization. NFC can join
eand U+0301 into the one code pointé, so a count of code points after NFC is closer to the count of clusters. But most clusters have no single code point, such as flags, emoji sequences and many Indic syllables. Normalization does not replace segmentation. - Words and sentences. UAX 29 also defines word boundaries and sentence boundaries, and the same APIs give them:
Intl.Segmenterwith"word", the wordBreakIteratorin Java and ICU, andunicode_wordsin Rust. Line breaks are in UAX 14. - Width on the screen. A cluster is one unit, but it can take one or two columns in a terminal. The column width is a separate property.
- String types built on clusters. Swift
StringandCharacter, and the .NETStringInfo, give clusters as the unit. Most other languages keep code units or code points as the unit and add clusters as an API. See string indexing.
Pitfalls
- A count of code points is not a count of characters.
len("👩🏽🚒")is 4 in Python,"👩🏽🚒".lengthis 7 in JavaScript, and the user sees one emoji. - A cut by code points or bytes can split a cluster.
"café"[:4]can lose the accent whenéis two code points, and a byte limit can cut an emoji in half. Cut at a cluster boundary. - A reverse by code points breaks clusters. The accent moves onto the next letter, and a flag
FRbecomesRF. See reverse a string. - Old rules in old libraries. The rules and the property data change with new versions of Unicode, as the revision for emoji sequences shows. The .NET documentation says that "prior to .NET 5, the StringInfo class had a bug causing some grapheme clusters to be handled incorrectly"6. Use a current library, and do not store cluster counts that must stay stable across versions.
- A hand-written segmenter. A sketch like the one in the Idea block is wrong for Hangul, for Indic scripts and for many emoji. Use the full rules from a library.
Cost
Segmentation reads the text from the start, so a count of clusters or a search for the i-th cluster is O(n). Each step looks up a property of each code point and applies a small state machine. To find a boundary at a random point is harder: UAX 29 says that "Random access introduces a further complication"1, because the rules can need context from before that point. An iterator that moves forward avoids this cost. For storage and for indexes, programs keep byte or code unit offsets, and they find cluster boundaries only when a user sees or edits the text.
History
Unicode Standard Annex #29 holds the rules. Its version for Unicode 5.1.0, dated 2008, already gave "two variants: legacy grapheme clusters and extended grapheme clusters"13, and it said that "The extended grapheme cluster boundaries are recommended for general processing"13. Emoji sequences came later. The revision for Unicode 9.0 "Added the new property values and rules for not breaking emoji sequences"14. Swift made the extended grapheme cluster its Character type, and later APIs such as Intl.Segmenter and Python unicodedata.iter_graphemes brought the rules into the standard libraries of other languages.
References
- Unicode Standard Annex, 3 Grapheme Cluster Boundaries; Table 1a; Table 2; 3.1.1 Grapheme Cluster Boundary Rules; 6.4 Random Access
- The Swift Programming Language, Strings and Characters, Extended Grapheme Clusters
- Intl.Segmenter, MDN Web Docs, Description
- Class BreakIterator, Java SE 25 API, Class description; Implementation Requirements
- Class Pattern, Java SE 25 API, Unicode Extended Grapheme matcher; Boundary matchers
- Character encoding in .NET, Grapheme clusters
- unicodedata, Unicode Database, Python 3.15 documentation, iter_graphemes; grapheme_cluster_break
- mrab-regex, the regex module for Python, README, Matching a single grapheme \X
- The Rust Programming Language, 8.2 Storing UTF-8 Encoded Text with Strings, Bytes and Scalar Values and Grapheme Clusters; Methods for Iterating Over Strings
- unicode-segmentation crate documentation, Crate description
- uniseg, Go package documentation, Grapheme Clusters
- Boundary Analysis, ICU User Guide, Character Boundary
- Unicode Standard Annex, 3 Grapheme Cluster Boundaries
- Unicode Standard Annex, Modifications, Revision 29
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag Q7FXFV Edit this page History Report an error Markdown