Taskcore
Count the graphemes of a string
Also called grapheme count, count user-perceived characters, extended grapheme cluster, count emoji, text elements, Intl.Segmenter, BreakIterator.
Count the extended grapheme clusters of a string, so that a letter with its combining marks, a flag and an emoji sequence each count as one.
- Evidence
- Code in 10 languages
Task
Count the graphemes of a string. A grapheme is an extended grapheme cluster of UAX #29, which is the unit for "user-perceived characters"1. The function count_graphemes(s) returns that number. For example, count_graphemes("e\u0301") is 1, because U+0301 is a combining mark, and the flag U+1F1EB U+1F1F7 is 1. A count of code points gives 2 for each of them.
The rules give a break between each two code points, except in these places:
| Rule | No break | Example |
|---|---|---|
| GB3 | between CR and LF | \r\n is 1 |
| GB9 | before Extend or ZWJ | e U+0301 is 1 |
| GB11 | between ZWJ and an emoji, after an emoji | U+1F469 U+200D U+1F4BB is 1 |
| GB12, GB13 | inside a pair of regional indicators | U+1F1EB U+1F1F7 is 1 |
GB4 and GB5 come before GB9: "Otherwise, break before and after controls"1. The Grapheme_Cluster_Break value of each code point is in the Unicode data file2, and Extended_Pictographic is in the emoji data file3.
The contract has a small set of code points: U+0000 to U+00FF, the combining marks U+0300 to U+036F, ZWJ, the variation selectors, the regional indicators, the skin tone modifiers and some emoji. The impls in Python, Go, Rust, C, C++ and Bash have a table for this set only. A full table has many more ranges, and also the rules for Hangul, Prepend, SpacingMark and Indic conjuncts1.
Solutions
| Language | Count |
|---|---|
Python, with iter_graphemes |
sum(1 for _ in unicodedata.iter_graphemes(s)) |
| JavaScript, TypeScript | [...new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(s)].length |
| Java | BreakIterator.getCharacterInstance() and a loop on next() |
| C# | new StringInfo(s).LengthInTextElements |
| Go, Rust, C, C++, Bash | the table and the rules of the contract |
- Python.
iter_graphemes"uses extended grapheme cluster rules defined by Unicode Standard Annex #29"4. Older versions of the module do not have the function, so the impl has its own table. - Java. "The default implementation of the character boundary analysis conforms to the Unicode Consortium's Extended Grapheme Cluster breaks"5.
- C#. ".NET defines a text element as a unit of text that is displayed as a single character, that is, a grapheme"6.
The impls with a table keep 3 values while they read the code points: the number of regional indicators that end at the previous code point, whether the previous code points are an emoji and Extend marks, and whether the previous code point is a ZWJ after that emoji.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: 0 graphemes.precomposedandcombining: U+00E9, andeU+0301, are each 1 grapheme.two-marksadds U+0302, and the count stays 1.leading-mark: U+0301 at the start has no base. It is a grapheme alone, so U+0301ais 2.crlfandlfcr: CR LF is 1, and LF CR is 2.cr-markandsoft-hyphen: a control does not take a combining mark, so CR U+0301 is 2. U+00AD is a control in the data file2, soaU+00ADbis 3.flag,three-indicatorsandtwo-flags: "do not break between regional indicator (RI) symbols if there is an odd number of RI characters before the break point"1. So 3 indicators are 2 graphemes, and 4 are 2.zwj-sequenceandzwj-after-letter: a ZWJ joins 2 emoji. After the lettera, the ZWJ joins thea, and the emoji is a new grapheme.skin-toneandvariation-selector: U+1F3FD and U+FE0F are Extend, so each pair is 1.
Pitfalls
- Python len counts code points. Each of these strings is 1 grapheme:
s = "e\u0301"
flag = "\U0001F1EB\U0001F1F7"
print(len(s), len(flag))
2 2
- JavaScript length counts UTF-16 code units. A spread counts code points. Only the segmenter gives 1 for a thumb with a skin tone.
Intl.Segmentergives "graphemes, words or sentences"7:
const s = "\u{1F44D}\u{1F3FD}";
const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
console.log(s.length, [...s].length, [...segmenter.segment(s)].length);
4 2 1
- Java codePointCount is not a grapheme count. A flag is 4 UTF-16 code units and 2 code points:
import java.text.BreakIterator;
public class Main {
public static void main(String[] args) {
String flag = "\ud83c\uddeb\ud83c\uddf7";
BreakIterator it = BreakIterator.getCharacterInstance();
it.setText(flag);
int n = 0;
it.first();
while (it.next() != BreakIterator.DONE) {
n++;
}
System.out.println(flag.length() + " " + flag.codePointCount(0, flag.length()) + " " + n);
}
}
4 2 1
- C# Length counts UTF-16 code units. The ZWJ sequence is 5 units and 1 text element:
using System;
using System.Globalization;
string s = "\U0001F469\u200d\U0001F4BB";
Console.WriteLine($"{s.Length} {new StringInfo(s).LengthInTextElements}");
5 1
- Go: a cut by runes drops the mark. "RuneCount returns the number of runes in p"8, so
eU+0301 is 2. The first rune alone ise, without its accent:
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "e\u0301"
r := []rune(s)
fmt.Println(utf8.RuneCountInString(s), string(r[:1]) == "e")
}
2 true
- Rust has no grapheme iterator in std. "Iteration over grapheme clusters may be what you actually want. This functionality is not provided by Rust's standard library, check crates.io instead"9.
chars().take(1)drops the accent too:
fn main() {
let s = "e\u{301}";
let first: String = s.chars().take(1).collect();
println!("{} {}", s.chars().count(), first == "e");
}
2 true
- C: the same text can have 2 lengths. U+00E9 is 2 bytes, and
eU+0301 is 3 bytes. Both are 1 grapheme. To compare them, normalize the text first:
#include <stdio.h>
#include <string.h>
int main(void) {
const char *composed = "\xc3\xa9";
const char *decomposed = "e\xcc\x81";
printf("%zu %zu\n", strlen(composed), strlen(decomposed));
return 0;
}
2 3
- C++: a cut at a byte count breaks a grapheme. The ZWJ sequence is 11 bytes. A cut at 4 bytes keeps only the first emoji:
#include <iostream>
#include <string>
int main() {
std::string s = "\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x92\xbb";
std::cout << s.size() << " " << s.substr(0, 4).size() << "\n";
}
11 4
- Bash: the locale decides what a character is.
${#parameter}"Substitutes the length in characters of the value of parameter"10, and LC_CTYPE "determines the interpretation of characters"10. In the C locale,eU+0301 gives 3:
s=$'e\xcc\x81'
LC_ALL=C
echo "${#s}"
3
Related tasks
- Find the length of a string: the length in bytes, in UTF-16 code units and in code points.
- Iterate over the characters of a string: the code points of a string in order.
- Reverse a string: a reverse by code points moves a combining mark to the wrong letter.
- Encode and decode UTF-8: the bytes of each code point.
- Normalize Unicode text: one form for the 2 ways to write U+00E9.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
"""Count the extended grapheme clusters of UAX #29 for the code points of the contract."""
CR, LF, CONTROL, EXTEND, ZWJ, RI, PICT, OTHER = range(8)
def _kind(c: int) -> int:
"""Return the Grapheme_Cluster_Break kind of c, or PICT for Extended_Pictographic."""
if c == 0x0D:
return CR
if c == 0x0A:
return LF
if c < 0x20 or 0x7F <= c <= 0x9F or c == 0xAD:
return CONTROL
if 0x300 <= c <= 0x36F or 0xFE00 <= c <= 0xFE0F or 0x1F3FB <= c <= 0x1F3FF:
return EXTEND
if c == 0x200D:
return ZWJ
if 0x1F1E6 <= c <= 0x1F1FF:
return RI
if c in (0xA9, 0xAE, 0x2764) or 0x1F400 <= c <= 0x1F4FD or 0x1F600 <= c <= 0x1F64F:
return PICT
return OTHER
def count_graphemes(s: str) -> int:
"""Return the number of graphemes in s. len(s) counts code points."""
n = 0
prev = None
ri_run = 0 # the number of regional indicators that end at prev
pict = False # prev ends Extended_Pictographic Extend*
zwj_after_pict = False # prev is a ZWJ after Extended_Pictographic Extend*
for ch in s:
k = _kind(ord(ch))
if prev is None:
join = False
elif prev == CR and k == LF:
join = True # GB3
elif prev in (CR, LF, CONTROL) or k in (CR, LF, CONTROL):
join = False # GB4, GB5
elif k in (EXTEND, ZWJ):
join = True # GB9
elif k == PICT and zwj_after_pict:
join = True # GB11
elif k == RI and ri_run % 2 == 1:
join = True # GB12, GB13
else:
join = False # GB999
if not join:
n += 1
zwj_after_pict = k == ZWJ and pict
pict = k == PICT or (k == EXTEND and pict)
ri_run = ri_run + 1 if k == RI else 0
prev = k
return n
test_count_graphemes.py 34 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
import pytest
from count_graphemes import count_graphemes
# A flag is 2 regional indicators, and U+1F469 U+200D U+1F4BB is 3 code points. Each of them is one grapheme.
CASES = {
"empty": ("", 0),
"ascii": ("abc", 3),
"precomposed": ("\u00e9", 1),
"emoji": ("\U0001f642", 1),
"combining": ("e\u0301", 1),
"two-marks": ("e\u0301\u0302", 1),
"leading-mark": ("\u0301a", 2),
"crlf": ("\r\n", 1),
"lfcr": ("\n\r", 2),
"cr-mark": ("\r\u0301", 2),
"soft-hyphen": ("a\u00adb", 3),
"flag": ("\U0001f1eb\U0001f1f7", 1),
"three-indicators": ("\U0001f1eb\U0001f1f7\U0001f1ea", 2),
"two-flags": ("\U0001f1eb\U0001f1f7\U0001f1ea\U0001f1f8", 2),
"zwj-sequence": ("\U0001f469\u200d\U0001f4bb", 1),
"zwj-after-letter": ("a\u200d\U0001f642", 2),
"skin-tone": ("\U0001f44d\U0001f3fd", 1),
"variation-selector": ("\u2764\ufe0f", 1),
}
@pytest.mark.parametrize("name", CASES)
def test_count_graphemes(name):
s, want = CASES[name]
assert count_graphemes(s) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
#include "count_graphemes.hpp"
#include <cstdint>
namespace {
enum class kind { other, cr, lf, control, extend, zwj, ri, pict };
// kind_of returns the Grapheme_Cluster_Break kind of c, or pict for
// Extended_Pictographic.
kind kind_of(std::uint32_t c) {
if (c == 0x0D) {
return kind::cr;
}
if (c == 0x0A) {
return kind::lf;
}
if (c < 0x20 || (c >= 0x7F && c <= 0x9F) || c == 0xAD) {
return kind::control;
}
if ((c >= 0x300 && c <= 0x36F) || (c >= 0xFE00 && c <= 0xFE0F) || (c >= 0x1F3FB && c <= 0x1F3FF)) {
return kind::extend;
}
if (c == 0x200D) {
return kind::zwj;
}
if (c >= 0x1F1E6 && c <= 0x1F1FF) {
return kind::ri;
}
if (c == 0xA9 || c == 0xAE || c == 0x2764 || (c >= 0x1F400 && c <= 0x1F4FD) || (c >= 0x1F600 && c <= 0x1F64F)) {
return kind::pict;
}
return kind::other;
}
// decode reads the UTF-8 sequence at s[i], and moves i past it.
std::uint32_t decode(std::string_view s, std::size_t &i) {
auto b0 = static_cast<unsigned char>(s[i]);
std::size_t n = b0 < 0x80 ? 1 : b0 < 0xE0 ? 2 : b0 < 0xF0 ? 3 : 4;
std::uint32_t c = n == 1 ? b0 : (b0 & (0x7Fu >> n));
for (std::size_t j = 1; j < n; j++) {
c = (c << 6) | (static_cast<unsigned char>(s[i + j]) & 0x3Fu);
}
i += n;
return c;
}
bool is_break_kind(kind k) {
return k == kind::cr || k == kind::lf || k == kind::control;
}
} // namespace
std::size_t count_graphemes(std::string_view s) {
std::size_t n = 0;
std::size_t ri_run = 0;
bool have_prev = false;
bool pict = false;
bool zwj_after_pict = false;
kind prev = kind::other;
for (std::size_t i = 0; i < s.size();) {
kind k = kind_of(decode(s, i));
bool join = false;
if (!have_prev) {
join = false;
} else if (prev == kind::cr && k == kind::lf) {
join = true; // GB3
} else if (is_break_kind(prev) || is_break_kind(k)) {
join = false; // GB4, GB5
} else if (k == kind::extend || k == kind::zwj) {
join = true; // GB9
} else if (k == kind::pict && zwj_after_pict) {
join = true; // GB11
} else if (k == kind::ri && ri_run % 2 == 1) {
join = true; // GB12, GB13
}
if (!join) {
n++;
}
zwj_after_pict = k == kind::zwj && pict;
pict = k == kind::pict || (k == kind::extend && pict);
ri_run = k == kind::ri ? ri_run + 1 : 0;
prev = k;
have_prev = true;
}
return n;
}
count_graphemes.hpp 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
#ifndef COUNT_GRAPHEMES_HPP
#define COUNT_GRAPHEMES_HPP
#include <cstddef>
#include <string_view>
// count_graphemes returns the number of extended grapheme clusters in the
// UTF-8 string s. s.size() counts bytes.
std::size_t count_graphemes(std::string_view s);
#endif
test_count_graphemes.cpp 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
#include "count_graphemes.hpp"
#include <iostream>
#include <string_view>
static int failures = 0;
static void check(std::string_view name, size_t got, size_t want) {
if (got != want) {
std::cerr << "case " << name << ": got " << got << ", want " << want << "\n";
failures++;
}
}
// A flag is 2 regional indicators, and U+1F469 U+200D U+1F4BB is 3 code points. Each of them is one grapheme.
int main() {
check("empty", count_graphemes(""), 0);
check("ascii", count_graphemes("abc"), 3);
check("precomposed", count_graphemes("\xc3\xa9"), 1);
check("emoji", count_graphemes("\xf0\x9f\x99\x82"), 1);
check("combining", count_graphemes("e\xcc\x81"), 1);
check("two-marks", count_graphemes("e\xcc\x81\xcc\x82"), 1);
check("leading-mark", count_graphemes("\xcc\x81" "a"), 2);
check("crlf", count_graphemes("\r\n"), 1);
check("lfcr", count_graphemes("\n\r"), 2);
check("cr-mark", count_graphemes("\r\xcc\x81"), 2);
check("soft-hyphen", count_graphemes("a\xc2\xad" "b"), 3);
check("flag", count_graphemes("\xf0\x9f\x87\xab\xf0\x9f\x87\xb7"), 1);
check("three-indicators", count_graphemes("\xf0\x9f\x87\xab\xf0\x9f\x87\xb7\xf0\x9f\x87\xaa"), 2);
check("two-flags", count_graphemes("\xf0\x9f\x87\xab\xf0\x9f\x87\xb7\xf0\x9f\x87\xaa\xf0\x9f\x87\xb8"), 2);
check("zwj-sequence", count_graphemes("\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x92\xbb"), 1);
check("zwj-after-letter", count_graphemes("a\xe2\x80\x8d\xf0\x9f\x99\x82"), 2);
check("skin-tone", count_graphemes("\xf0\x9f\x91\x8d\xf0\x9f\x8f\xbd"), 1);
check("variation-selector", count_graphemes("\xe2\x9d\xa4\xef\xb8\x8f"), 1);
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
import java.text.BreakIterator;
final class GraphemeCount {
private GraphemeCount() {}
// countGraphemes returns the number of extended grapheme clusters in s. The
// character instance of BreakIterator finds the grapheme cluster boundaries.
static int countGraphemes(String s) {
BreakIterator it = BreakIterator.getCharacterInstance();
it.setText(s);
int n = 0;
it.first();
while (it.next() != BreakIterator.DONE) {
n++;
}
return n;
}
}
GraphemeCountTest.java 40 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class GraphemeCountTest {
// A flag is 2 regional indicators, and U+1F469 U+200D U+1F4BB is 3 code points. Each of them is one grapheme.
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("empty", "", 0),
Arguments.of("ascii", "abc", 3),
Arguments.of("precomposed", "\u00e9", 1),
Arguments.of("emoji", "\ud83d\ude42", 1),
Arguments.of("combining", "e\u0301", 1),
Arguments.of("two-marks", "e\u0301\u0302", 1),
Arguments.of("leading-mark", "\u0301a", 2),
Arguments.of("crlf", "\r\n", 1),
Arguments.of("lfcr", "\n\r", 2),
Arguments.of("cr-mark", "\r\u0301", 2),
Arguments.of("soft-hyphen", "a\u00adb", 3),
Arguments.of("flag", "\ud83c\uddeb\ud83c\uddf7", 1),
Arguments.of("three-indicators", "\ud83c\uddeb\ud83c\uddf7\ud83c\uddea", 2),
Arguments.of("two-flags", "\ud83c\uddeb\ud83c\uddf7\ud83c\uddea\ud83c\uddf8", 2),
Arguments.of("zwj-sequence", "\ud83d\udc69\u200d\ud83d\udcbb", 1),
Arguments.of("zwj-after-letter", "a\u200d\ud83d\ude42", 2),
Arguments.of("skin-tone", "\ud83d\udc4d\ud83c\udffd", 1),
Arguments.of("variation-selector", "\u2764\ufe0f", 1));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void countGraphemes(String name, String s, int want) {
assertEquals(want, GraphemeCount.countGraphemes(s));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
#include "count_graphemes.h"
#include <stdint.h>
enum kind { OTHER, CR, LF, CONTROL, EXTEND, ZWJ, RI, PICT };
// kind returns the Grapheme_Cluster_Break kind of c, or PICT for
// Extended_Pictographic.
static enum kind kind(uint32_t c) {
if (c == 0x0D) {
return CR;
}
if (c == 0x0A) {
return LF;
}
if (c < 0x20 || (c >= 0x7F && c <= 0x9F) || c == 0xAD) {
return CONTROL;
}
if ((c >= 0x300 && c <= 0x36F) || (c >= 0xFE00 && c <= 0xFE0F) || (c >= 0x1F3FB && c <= 0x1F3FF)) {
return EXTEND;
}
if (c == 0x200D) {
return ZWJ;
}
if (c >= 0x1F1E6 && c <= 0x1F1FF) {
return RI;
}
if (c == 0xA9 || c == 0xAE || c == 0x2764 || (c >= 0x1F400 && c <= 0x1F4FD) || (c >= 0x1F600 && c <= 0x1F64F)) {
return PICT;
}
return OTHER;
}
// decode reads the UTF-8 sequence at *p, and moves *p past it.
static uint32_t decode(const unsigned char **p) {
const unsigned char *b = *p;
size_t n = b[0] < 0x80 ? 1 : b[0] < 0xE0 ? 2 : b[0] < 0xF0 ? 3 : 4;
uint32_t c = n == 1 ? b[0] : (uint32_t)(b[0] & (0x7F >> n));
for (size_t i = 1; i < n; i++) {
c = (c << 6) | (uint32_t)(b[i] & 0x3F);
}
*p = b + n;
return c;
}
size_t count_graphemes(const char *s) {
const unsigned char *p = (const unsigned char *)s;
size_t n = 0;
size_t ri_run = 0;
int have_prev = 0;
int pict = 0;
int zwj_after_pict = 0;
enum kind prev = OTHER;
while (*p != 0) {
enum kind k = kind(decode(&p));
int join = 0;
if (!have_prev) {
join = 0;
} else if (prev == CR && k == LF) {
join = 1; // GB3
} else if (prev == CR || prev == LF || prev == CONTROL || k == CR || k == LF || k == CONTROL) {
join = 0; // GB4, GB5
} else if (k == EXTEND || k == ZWJ) {
join = 1; // GB9
} else if (k == PICT && zwj_after_pict) {
join = 1; // GB11
} else if (k == RI && ri_run % 2 == 1) {
join = 1; // GB12, GB13
}
if (!join) {
n++;
}
zwj_after_pict = k == ZWJ && pict;
pict = k == PICT || (k == EXTEND && pict);
ri_run = k == RI ? ri_run + 1 : 0;
prev = k;
have_prev = 1;
}
return n;
}
count_graphemes.h 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
#ifndef COUNT_GRAPHEMES_H
#define COUNT_GRAPHEMES_H
#include <stddef.h>
// count_graphemes returns the number of extended grapheme clusters in the
// UTF-8 string s. strlen(s) counts bytes.
size_t count_graphemes(const char *s);
#endif
test_count_graphemes.c 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
#include "count_graphemes.h"
#include <stdio.h>
static int failures = 0;
static void check(const char *name, size_t got, size_t want) {
if (got != want) {
fprintf(stderr, "case %s: got %lu, want %lu\n", name, (unsigned long)got, (unsigned long)want);
failures++;
}
}
// A flag is 2 regional indicators, and U+1F469 U+200D U+1F4BB is 3 code points. Each of them is one grapheme.
int main(void) {
check("empty", count_graphemes(""), 0);
check("ascii", count_graphemes("abc"), 3);
check("precomposed", count_graphemes("\xc3\xa9"), 1);
check("emoji", count_graphemes("\xf0\x9f\x99\x82"), 1);
check("combining", count_graphemes("e\xcc\x81"), 1);
check("two-marks", count_graphemes("e\xcc\x81\xcc\x82"), 1);
check("leading-mark", count_graphemes("\xcc\x81" "a"), 2);
check("crlf", count_graphemes("\r\n"), 1);
check("lfcr", count_graphemes("\n\r"), 2);
check("cr-mark", count_graphemes("\r\xcc\x81"), 2);
check("soft-hyphen", count_graphemes("a\xc2\xad" "b"), 3);
check("flag", count_graphemes("\xf0\x9f\x87\xab\xf0\x9f\x87\xb7"), 1);
check("three-indicators", count_graphemes("\xf0\x9f\x87\xab\xf0\x9f\x87\xb7\xf0\x9f\x87\xaa"), 2);
check("two-flags", count_graphemes("\xf0\x9f\x87\xab\xf0\x9f\x87\xb7\xf0\x9f\x87\xaa\xf0\x9f\x87\xb8"), 2);
check("zwj-sequence", count_graphemes("\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x92\xbb"), 1);
check("zwj-after-letter", count_graphemes("a\xe2\x80\x8d\xf0\x9f\x99\x82"), 2);
check("skin-tone", count_graphemes("\xf0\x9f\x91\x8d\xf0\x9f\x8f\xbd"), 1);
check("variation-selector", count_graphemes("\xe2\x9d\xa4\xef\xb8\x8f"), 1);
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
using System.Globalization;
public static class Graphemes
{
// Count returns the number of extended grapheme clusters in s. A text
// element of StringInfo is a grapheme. s.Length counts UTF-16 code units.
public static int Count(string s)
{
return new StringInfo(s).LengthInTextElements;
}
}
GraphemeCountTests.cs 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
using Xunit;
public sealed class GraphemeCountTests
{
// A flag is 2 regional indicators, and U+1F469 U+200D U+1F4BB is 3 code points. Each of them is one grapheme.
public static TheoryData<string, string, int> Cases => new()
{
{ "empty", "", 0 },
{ "ascii", "abc", 3 },
{ "precomposed", "\u00e9", 1 },
{ "emoji", "\U0001f642", 1 },
{ "combining", "e\u0301", 1 },
{ "two-marks", "e\u0301\u0302", 1 },
{ "leading-mark", "\u0301a", 2 },
{ "crlf", "\r\n", 1 },
{ "lfcr", "\n\r", 2 },
{ "cr-mark", "\r\u0301", 2 },
{ "soft-hyphen", "a\u00adb", 3 },
{ "flag", "\U0001f1eb\U0001f1f7", 1 },
{ "three-indicators", "\U0001f1eb\U0001f1f7\U0001f1ea", 2 },
{ "two-flags", "\U0001f1eb\U0001f1f7\U0001f1ea\U0001f1f8", 2 },
{ "zwj-sequence", "\U0001f469\u200d\U0001f4bb", 1 },
{ "zwj-after-letter", "a\u200d\U0001f642", 2 },
{ "skin-tone", "\U0001f44d\U0001f3fd", 1 },
{ "variation-selector", "\u2764\ufe0f", 1 },
};
[Theory]
[MemberData(nameof(Cases))]
public void CountGraphemes(string name, string s, int want)
{
Assert.NotNull(name);
Assert.Equal(want, Graphemes.Count(s));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
// countGraphemes returns the number of extended grapheme clusters in s.
// s.length counts UTF-16 code units, and [...s].length counts code points.
export function countGraphemes(s) {
return [...segmenter.segment(s)].length;
}
count_graphemes.test.js 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { countGraphemes } from "./count_graphemes.js";
// A flag is 2 regional indicators, and U+1F469 U+200D U+1F4BB is 3 code points. Each of them is one grapheme.
const cases = [
["empty", "", 0],
["ascii", "abc", 3],
["precomposed", "\u00e9", 1],
["emoji", "\u{1f642}", 1],
["combining", "e\u0301", 1],
["two-marks", "e\u0301\u0302", 1],
["leading-mark", "\u0301a", 2],
["crlf", "\r\n", 1],
["lfcr", "\n\r", 2],
["cr-mark", "\r\u0301", 2],
["soft-hyphen", "a\u00adb", 3],
["flag", "\u{1f1eb}\u{1f1f7}", 1],
["three-indicators", "\u{1f1eb}\u{1f1f7}\u{1f1ea}", 2],
["two-flags", "\u{1f1eb}\u{1f1f7}\u{1f1ea}\u{1f1f8}", 2],
["zwj-sequence", "\u{1f469}\u200d\u{1f4bb}", 1],
["zwj-after-letter", "a\u200d\u{1f642}", 2],
["skin-tone", "\u{1f44d}\u{1f3fd}", 1],
["variation-selector", "\u2764\ufe0f", 1],
];
for (const [name, s, want] of cases) {
test(name, () => {
assert.equal(countGraphemes(s), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
// countGraphemes returns the number of extended grapheme clusters in s.
// s.length counts UTF-16 code units, and [...s].length counts code points.
export function countGraphemes(s: string): number {
return [...segmenter.segment(s)].length;
}
count_graphemes.test.ts 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { countGraphemes } from "./count_graphemes.ts";
// A flag is 2 regional indicators, and U+1F469 U+200D U+1F4BB is 3 code points. Each of them is one grapheme.
const cases: [string, string, number][] = [
["empty", "", 0],
["ascii", "abc", 3],
["precomposed", "\u00e9", 1],
["emoji", "\u{1f642}", 1],
["combining", "e\u0301", 1],
["two-marks", "e\u0301\u0302", 1],
["leading-mark", "\u0301a", 2],
["crlf", "\r\n", 1],
["lfcr", "\n\r", 2],
["cr-mark", "\r\u0301", 2],
["soft-hyphen", "a\u00adb", 3],
["flag", "\u{1f1eb}\u{1f1f7}", 1],
["three-indicators", "\u{1f1eb}\u{1f1f7}\u{1f1ea}", 2],
["two-flags", "\u{1f1eb}\u{1f1f7}\u{1f1ea}\u{1f1f8}", 2],
["zwj-sequence", "\u{1f469}\u200d\u{1f4bb}", 1],
["zwj-after-letter", "a\u200d\u{1f642}", 2],
["skin-tone", "\u{1f44d}\u{1f3fd}", 1],
["variation-selector", "\u2764\ufe0f", 1],
];
for (const [name, s, want] of cases) {
test(name, () => {
assert.equal(countGraphemes(s), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
// Package graphemes counts the extended grapheme clusters of UAX #29 for the
// code points of the contract.
package graphemes
const (
other = iota
cr
lf
control
extend
zwj
ri
pict
)
// kind returns the Grapheme_Cluster_Break kind of c, or pict for
// Extended_Pictographic.
func kind(c rune) int {
switch {
case c == 0x0D:
return cr
case c == 0x0A:
return lf
case c < 0x20 || (c >= 0x7F && c <= 0x9F) || c == 0xAD:
return control
case (c >= 0x300 && c <= 0x36F) || (c >= 0xFE00 && c <= 0xFE0F) || (c >= 0x1F3FB && c <= 0x1F3FF):
return extend
case c == 0x200D:
return zwj
case c >= 0x1F1E6 && c <= 0x1F1FF:
return ri
case c == 0xA9 || c == 0xAE || c == 0x2764 || (c >= 0x1F400 && c <= 0x1F4FD) || (c >= 0x1F600 && c <= 0x1F64F):
return pict
}
return other
}
// CountGraphemes returns the number of graphemes in s.
// utf8.RuneCountInString counts code points.
func CountGraphemes(s string) int {
n, prev, riRun := 0, -1, 0
isPict, zwjAfterPict := false, false
for _, c := range s {
k := kind(c)
join := false
switch {
case prev < 0:
case prev == cr && k == lf: // GB3
join = true
case prev == cr || prev == lf || prev == control || k == cr || k == lf || k == control: // GB4, GB5
case k == extend || k == zwj: // GB9
join = true
case k == pict && zwjAfterPict: // GB11
join = true
case k == ri && riRun%2 == 1: // GB12, GB13
join = true
}
if !join {
n++
}
zwjAfterPict = k == zwj && isPict
isPict = k == pict || (k == extend && isPict)
if k == ri {
riRun++
} else {
riRun = 0
}
prev = k
}
return n
}
count_graphemes_test.go 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
package graphemes
import "testing"
// A flag is 2 regional indicators, and U+1F469 U+200D U+1F4BB is 3 code points. Each of them is one grapheme.
var cases = []struct {
name, s string
want int
}{
{"empty", "", 0},
{"ascii", "abc", 3},
{"precomposed", "\u00e9", 1},
{"emoji", "\U0001f642", 1},
{"combining", "e\u0301", 1},
{"two-marks", "e\u0301\u0302", 1},
{"leading-mark", "\u0301a", 2},
{"crlf", "\r\n", 1},
{"lfcr", "\n\r", 2},
{"cr-mark", "\r\u0301", 2},
{"soft-hyphen", "a\u00adb", 3},
{"flag", "\U0001f1eb\U0001f1f7", 1},
{"three-indicators", "\U0001f1eb\U0001f1f7\U0001f1ea", 2},
{"two-flags", "\U0001f1eb\U0001f1f7\U0001f1ea\U0001f1f8", 2},
{"zwj-sequence", "\U0001f469\u200d\U0001f4bb", 1},
{"zwj-after-letter", "a\u200d\U0001f642", 2},
{"skin-tone", "\U0001f44d\U0001f3fd", 1},
{"variation-selector", "\u2764\ufe0f", 1},
}
func TestCountGraphemes(t *testing.T) {
for _, c := range cases {
if got := CountGraphemes(c.s); got != c.want {
t.Errorf("%s: got %d, want %d", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
#[derive(Clone, Copy, PartialEq)]
enum Kind {
Cr,
Lf,
Control,
Extend,
Zwj,
Ri,
Pict,
Other,
}
/// Returns the Grapheme_Cluster_Break kind of `c`, or `Pict` for
/// Extended_Pictographic.
fn kind(c: char) -> Kind {
match u32::from(c) {
0x0D => Kind::Cr,
0x0A => Kind::Lf,
0x00..=0x1F | 0x7F..=0x9F | 0xAD => Kind::Control,
0x300..=0x36F | 0xFE00..=0xFE0F | 0x1F3FB..=0x1F3FF => Kind::Extend,
0x200D => Kind::Zwj,
0x1F1E6..=0x1F1FF => Kind::Ri,
0xA9 | 0xAE | 0x2764 | 0x1F400..=0x1F4FD | 0x1F600..=0x1F64F => Kind::Pict,
_ => Kind::Other,
}
}
/// Returns the number of graphemes in `s`. `s.chars().count()` counts code
/// points, and `s.len()` counts bytes.
pub fn count_graphemes(s: &str) -> usize {
let mut n = 0;
let mut prev: Option<Kind> = None;
let mut ri_run = 0;
let mut pict = false;
let mut zwj_after_pict = false;
for c in s.chars() {
let k = kind(c);
let join = match prev {
None => false,
Some(Kind::Cr) if k == Kind::Lf => true, // GB3
Some(Kind::Cr | Kind::Lf | Kind::Control) => false, // GB4
Some(_) if matches!(k, Kind::Cr | Kind::Lf | Kind::Control) => false, // GB5
Some(_) if matches!(k, Kind::Extend | Kind::Zwj) => true, // GB9
Some(_) if k == Kind::Pict && zwj_after_pict => true, // GB11
Some(_) if k == Kind::Ri && ri_run % 2 == 1 => true, // GB12, GB13
Some(_) => false, // GB999
};
if !join {
n += 1;
}
zwj_after_pict = k == Kind::Zwj && pict;
pict = k == Kind::Pict || (k == Kind::Extend && pict);
ri_run = if k == Kind::Ri { ri_run + 1 } else { 0 };
prev = Some(k);
}
n
}
tests/count_graphemes_test.rs 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
use algo_count_the_graphemes_of_a_string::count_graphemes;
// A flag is 2 regional indicators, and U+1F469 U+200D U+1F4BB is 3 code points. Each of them is one grapheme.
#[test]
fn cases() {
let cases: [(&str, &str, usize); 18] = [
("empty", "", 0),
("ascii", "abc", 3),
("precomposed", "\u{e9}", 1),
("emoji", "\u{1f642}", 1),
("combining", "e\u{301}", 1),
("two-marks", "e\u{301}\u{302}", 1),
("leading-mark", "\u{301}a", 2),
("crlf", "\r\n", 1),
("lfcr", "\n\r", 2),
("cr-mark", "\r\u{301}", 2),
("soft-hyphen", "a\u{ad}b", 3),
("flag", "\u{1f1eb}\u{1f1f7}", 1),
("three-indicators", "\u{1f1eb}\u{1f1f7}\u{1f1ea}", 2),
("two-flags", "\u{1f1eb}\u{1f1f7}\u{1f1ea}\u{1f1f8}", 2),
("zwj-sequence", "\u{1f469}\u{200d}\u{1f4bb}", 1),
("zwj-after-letter", "a\u{200d}\u{1f642}", 2),
("skin-tone", "\u{1f44d}\u{1f3fd}", 1),
("variation-selector", "\u{2764}\u{fe0f}", 1),
];
for (name, s, want) in cases {
assert_eq!(count_graphemes(s), want, "{name}");
}
}
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
# _grapheme_kind C: sets K to the Grapheme_Cluster_Break kind of the code
# point C: cr, lf, control, extend, zwj, ri, pict (Extended_Pictographic) or
# other.
_grapheme_kind() {
local c=$1
if ((c == 0x0D)); then
K=cr
elif ((c == 0x0A)); then
K=lf
elif ((c < 0x20 || (c >= 0x7F && c <= 0x9F) || c == 0xAD)); then
K=control
elif (((c >= 0x300 && c <= 0x36F) || (c >= 0xFE00 && c <= 0xFE0F) || (c >= 0x1F3FB && c <= 0x1F3FF))); then
K=extend
elif ((c == 0x200D)); then
K=zwj
elif ((c >= 0x1F1E6 && c <= 0x1F1FF)); then
K=ri
elif ((c == 0xA9 || c == 0xAE || c == 0x2764 || (c >= 0x1F400 && c <= 0x1F4FD) || (c >= 0x1F600 && c <= 0x1F64F))); then
K=pict
else
K=other
fi
}
# count_graphemes S: prints the number of extended grapheme clusters in the
# UTF-8 string S. In the C locale, ${#S} counts bytes, so the function decodes
# the code points from the bytes.
count_graphemes() {
(
LC_ALL=C
s=$1
len=${#s}
n=0 i=0 prev='' ri_run=0 pict=0 zwj_after_pict=0
while ((i < len)); do
printf -v b '%d' "'${s:i:1}"
((b < 0)) && ((b += 256))
if ((b < 0x80)); then
m=1
elif ((b < 0xE0)); then
m=2
elif ((b < 0xF0)); then
m=3
else
m=4
fi
((c = m == 1 ? b : b & (0x7F >> m)))
for ((j = 1; j < m; j++)); do
printf -v b '%d' "'${s:i+j:1}"
((b < 0)) && ((b += 256))
((c = (c << 6) | (b & 0x3F)))
done
((i += m))
_grapheme_kind "$c"
join=0
if [[ -z $prev ]]; then
join=0
elif [[ $prev == cr && $K == lf ]]; then
join=1 # GB3
elif [[ $prev =~ ^(cr|lf|control)$ || $K =~ ^(cr|lf|control)$ ]]; then
join=0 # GB4, GB5
elif [[ $K == extend || $K == zwj ]]; then
join=1 # GB9
elif [[ $K == pict ]] && ((zwj_after_pict)); then
join=1 # GB11
elif [[ $K == ri ]] && ((ri_run % 2 == 1)); then
join=1 # GB12, GB13
fi
((join)) || ((n += 1))
zwj_after_pict=0
[[ $K == zwj ]] && ((pict)) && zwj_after_pict=1
if [[ $K == pict ]]; then
pict=1
elif [[ $K != extend ]]; then
pict=0
fi
if [[ $K == ri ]]; then
((ri_run += 1))
else
ri_run=0
fi
prev=$K
done
echo "$n"
)
}
test_count_graphemes.bats 34 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-the-graphemes-of-a-string/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/count_graphemes.sh"
}
check() { # check C WANT
run count_graphemes "$1"
[ "$status" -eq 0 ]
[ "$output" = "$2" ]
}
# Each argument is a string of UTF-8 bytes.
@test "empty" { check '' 0; }
@test "ascii" { check 'abc' 3; }
@test "precomposed" { check $'\xc3\xa9' 1; }
@test "emoji" { check $'\xf0\x9f\x99\x82' 1; }
@test "combining" { check $'e\xcc\x81' 1; }
@test "two-marks" { check $'e\xcc\x81\xcc\x82' 1; }
@test "leading-mark" { check $'\xcc\x81a' 2; }
@test "crlf" { check $'\r\n' 1; }
@test "lfcr" { check $'\n\r' 2; }
@test "cr-mark" { check $'\r\xcc\x81' 2; }
@test "soft-hyphen" { check $'a\xc2\xadb' 3; }
@test "flag" { check $'\xf0\x9f\x87\xab\xf0\x9f\x87\xb7' 1; }
@test "three-indicators" { check $'\xf0\x9f\x87\xab\xf0\x9f\x87\xb7\xf0\x9f\x87\xaa' 2; }
@test "two-flags" { check $'\xf0\x9f\x87\xab\xf0\x9f\x87\xb7\xf0\x9f\x87\xaa\xf0\x9f\x87\xb8' 2; }
@test "zwj-sequence" { check $'\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x92\xbb' 1; }
@test "zwj-after-letter" { check $'a\xe2\x80\x8d\xf0\x9f\x99\x82' 2; }
@test "skin-tone" { check $'\xf0\x9f\x91\x8d\xf0\x9f\x8f\xbd' 1; }
@test "variation-selector" { check $'\xe2\x9d\xa4\xef\xb8\x8f' 1; }
References
- Unicode Standard Annex, 3.1.1 Grapheme Cluster Boundary Rules
- Unicode Character Database, GraphemeBreakProperty.txt, Unicode 18.0.0
- Unicode Character Database, emoji-data.txt, Extended_Pictographic
- The Python Standard Library, unicodedata, iter_graphemes
- Java SE 25 API, Class BreakIterator, Implementation Requirements
- .NET API reference, StringInfo class, Remarks
- MDN Web Docs, Intl.Segmenter, Description
- Go standard library, package unicode/utf8, RuneCount
- Rust standard library, primitive type str, chars
- Bash Reference Manual, 3.5.3 Shell Parameter Expansion; 5.2 Bash Variables
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 |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag G23VJ9 Edit this page History Report an error Markdown