grapheme_strlen

grapheme_strlen(string $string): int|false|null

Counts grapheme clusters (user-perceived characters): strlen counts bytes, mb_strlen counts code points, grapheme_strlen counts graphemes — precomposed é and decomposed é both count as 1, and the ZWJ family emoji counts as a single grapheme.

C C23

C23
#include <stdio.h>
#include <string.h>

/* Decode one UTF-8 code point; returns its byte length (0 at end of input) */
static size_t decode_utf8(const unsigned char *s, size_t n, unsigned *cp) {
    if (n == 0) return 0;
    if (s[0] < 0x80) { *cp = s[0]; return 1; }
    if ((s[0] & 0xE0) == 0xC0 && n >= 2) { *cp = ((s[0] & 0x1F) << 6) | (s[1] & 0x3F); return 2; }
    if ((s[0] & 0xF0) == 0xE0 && n >= 3) { *cp = ((s[0] & 0x0F) << 12) | ((s[1] & 0x3F) << 6) | (s[2] & 0x3F); return 3; }
    if ((s[0] & 0xF8) == 0xF0 && n >= 4) { *cp = ((s[0] & 0x07) << 18) | ((s[1] & 0x3F) << 12) | ((s[2] & 0x3F) << 6) | (s[3] & 0x3F); return 4; }
    *cp = 0xFFFD; return 1; /* invalid lead byte: substitute one byte */
}

/* Simplified Grapheme_Cluster_Break: CR / LF / Extend / ZWJ only —
   enough for these demo strings (full UAX #29 needs ICU or libunistring) */
static int graphemes(const char *str) {
    const unsigned char *s = (const unsigned char *)str;
    size_t n = strlen(str), i = 0;
    int count = 0, have_prev = 0;
    unsigned prev = 0, cp;
    while (i < n) {
        i += decode_utf8(s + i, n - i, &cp);
        if (cp >= 0x0300 && cp <= 0x036F) continue;            /* Extend: stay in the cluster */
        if (cp == 0x200D) { prev = cp; have_prev = 1; continue; }              /* ZWJ: joiner stays in the cluster */
        if (have_prev && cp == 0x0A && prev == 0x0D) { prev = cp; continue; } /* CRLF = one cluster */
        if (have_prev && prev == 0x200D) { prev = cp; continue; }             /* base char after ZWJ joins */
        count++;
        prev = cp;
        have_prev = 1;
    }
    return count;
}

static int codepoints(const char *str) {
    const unsigned char *s = (const unsigned char *)str;
    size_t n = strlen(str), i = 0;
    int count = 0;
    unsigned cp;
    while (i < n) { i += decode_utf8(s + i, n - i, &cp); count++; }
    return count;
}

int main(void) {
    const char *samples[][2] = {
        {"ascii", "abc"},
        {"pre", "caf\xC3\xA9"},     /* é precomposed (U+00E9) */
        {"decomp", "cafe\xCC\x81"}, /* é decomposed: e + U+0301 */
        {"zwj", "a\xF0\x9F\x91\xA8\xE2\x80\x8D\xF0\x9F\x91\xA9\xE2\x80\x8D\xF0\x9F\x91\xA7" "b"},
    };
    for (int k = 0; k < 4; k++) {
        printf("%s: bytes=%zu chars=%d graphemes=%d\n",
               samples[k][0], strlen(samples[k][1]), codepoints(samples[k][1]), graphemes(samples[k][1]));
    }
    return 0;
}
Output
ascii: bytes=3 chars=3 graphemes=3
pre: bytes=5 chars=4 graphemes=4
decomp: bytes=6 chars=5 graphemes=4
zwj: bytes=20 chars=7 graphemes=3

C++ C++26

C++26
#include <cstdio>
#include <string>
#include <utility>

// Decode one UTF-8 code point; returns its byte length (0 at end of input)
static size_t decodeUtf8(const unsigned char *s, size_t n, unsigned &cp) {
    if (n == 0) return 0;
    if (s[0] < 0x80) { cp = s[0]; return 1; }
    if ((s[0] & 0xE0) == 0xC0 && n >= 2) { cp = ((s[0] & 0x1F) << 6) | (s[1] & 0x3F); return 2; }
    if ((s[0] & 0xF0) == 0xE0 && n >= 3) { cp = ((s[0] & 0x0F) << 12) | ((s[1] & 0x3F) << 6) | (s[2] & 0x3F); return 3; }
    if ((s[0] & 0xF8) == 0xF0 && n >= 4) { cp = ((s[0] & 0x07) << 18) | ((s[1] & 0x3F) << 12) | ((s[2] & 0x3F) << 6) | (s[3] & 0x3F); return 4; }
    cp = 0xFFFD; return 1;
}

// Simplified Grapheme_Cluster_Break: CR / LF / Extend / ZWJ only —
// enough for these demo strings (full UAX #29 needs ICU)
static int graphemes(const std::string &str) {
    const unsigned char *s = reinterpret_cast<const unsigned char *>(str.data());
    size_t n = str.size(), i = 0;
    int count = 0, havePrev = 0;
    unsigned prev = 0, cp;
    while (i < n) {
        i += decodeUtf8(s + i, n - i, cp);
        if (cp >= 0x0300 && cp <= 0x036F) continue;                 // Extend: stay in the cluster
        if (cp == 0x200D) { prev = cp; havePrev = 1; continue; }    // ZWJ: joiner stays in the cluster
        if (havePrev && cp == 0x0A && prev == 0x0D) { prev = cp; continue; } // CRLF = one cluster
        if (havePrev && prev == 0x200D) { prev = cp; continue; }    // base char after ZWJ joins
        count++;
        prev = cp;
        havePrev = 1;
    }
    return count;
}

static int codepoints(const std::string &str) {
    const unsigned char *s = reinterpret_cast<const unsigned char *>(str.data());
    size_t n = str.size(), i = 0;
    int count = 0;
    unsigned cp;
    while (i < n) { i += decodeUtf8(s + i, n - i, cp); count++; }
    return count;
}

int main() {
    const std::pair<const char *, std::string> samples[] = {
        {"ascii", "abc"},
        {"pre", "caf\xC3\xA9"},     // é precomposed (U+00E9)
        {"decomp", "cafe\xCC\x81"}, // é decomposed: e + U+0301
        {"zwj", "a\xF0\x9F\x91\xA8\xE2\x80\x8D\xF0\x9F\x91\xA9\xE2\x80\x8D\xF0\x9F\x91\xA7" "b"},
    };
    for (auto &[label, s] : samples) {
        std::printf("%s: bytes=%zu chars=%d graphemes=%d\n", label, s.size(), codepoints(s), graphemes(s));
    }
    return 0;
}
Output
ascii: bytes=3 chars=3 graphemes=3
pre: bytes=5 chars=4 graphemes=4
decomp: bytes=6 chars=5 graphemes=4
zwj: bytes=20 chars=7 graphemes=3

C# v11.0.100

v11.0.100
using System.Globalization;

string[][] samples = {
    new[] { "ascii", "abc" },
    new[] { "pre", "café" },
    new[] { "decomp", "cafe\u0301" },
    new[] { "zwj", "a👨‍👩‍👧b" },
};
foreach (var p in samples)
{
    // StringInfo.LengthInTextElements counts text elements ≈ grapheme clusters
    Console.WriteLine($"{p[0]}: chars={p[1].Length} textElements={new StringInfo(p[1]).LengthInTextElements}");
}
Output
ascii: chars=3 textElements=3
pre: chars=4 textElements=4
decomp: chars=5 textElements=4
zwj: chars=10 textElements=3

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"unicode/utf8"
)

// no grapheme segmentation in the stdlib — hand-roll the simplified
// Grapheme_Cluster_Break rule: CR / LF / Extend / ZWJ only
func graphemes(s string) int {
	count, prev := 0, rune(0)
	for _, r := range s { // range decodes UTF-8 into runes (code points)
		switch {
		case r >= 0x0300 && r <= 0x036F: // Extend: stay in the cluster
		case r == 0x200D: // ZWJ: joiner stays in the cluster
		case r == 0x0A && prev == 0x0D: // LF right after CR: one cluster
		case prev == 0x200D: // base char right after ZWJ: join the chain
		default:
			count++
		}
		prev = r
	}
	return count
}

func main() {
	for _, tc := range []struct{ label, s string }{
		{"ascii", "abc"},
		{"pre", "café"},
		{"decomp", "café"},
		{"zwj", "a👨‍👩‍👧b"},
	} {
		fmt.Printf("%s: runes=%d graphemes=%d\n", tc.label, utf8.RuneCountInString(tc.s), graphemes(tc.s))
	}
}
Output
ascii: runes=3 graphemes=3
pre: runes=4 graphemes=4
decomp: runes=5 graphemes=4
zwj: runes=7 graphemes=3

Java v27.0.1

v27.0.1
import java.text.BreakIterator;

public class Main {
    // BreakIterator.getCharacterInstance walks "character" boundaries ≈ grapheme clusters
    static int graphemes(String s) {
        BreakIterator it = BreakIterator.getCharacterInstance();
        it.setText(s);
        int count = 0;
        for (int end = it.next(); end != BreakIterator.DONE; end = it.next()) {
            count++;
        }
        return count;
    }

    public static void main(String[] args) {
        String[][] samples = {
            {"ascii", "abc"},
            {"pre", "café"},
            {"decomp", "cafe\u0301"},
            {"zwj", "a👨‍👩‍👧b"},
        };
        for (String[] p : samples) {
            System.out.printf("%s: chars=%d graphemes=%d%n",
                p[0], p[1].codePointCount(0, p[1].length()), graphemes(p[1]));
        }
    }
}
Output
ascii: chars=3 graphemes=3
pre: chars=4 graphemes=4
decomp: chars=5 graphemes=4
zwj: chars=7 graphemes=3

JavaScript v26.13.1

v26.13.1
// Intl.Segmenter (ES2022, granularity "grapheme"): the native grapheme counter
const seg = new Intl.Segmenter("en", { granularity: "grapheme" });
const graphemes = (s) => [...seg.segment(s)].length;
const samples = [["ascii", "abc"], ["pre", "café"], ["decomp", "cafe\u0301"], ["zwj", "a👨‍👩‍👧b"]];
for (const [label, s] of samples) {
  console.log(`${label}: codePoints=${[...s].length} graphemes=${graphemes(s)}`);
}
Output
ascii: codePoints=3 graphemes=3
pre: codePoints=4 graphemes=4
decomp: codePoints=5 graphemes=4
zwj: codePoints=7 graphemes=3

PHP v8.6.0

v8.6.0
// Three tiers of "length": bytes vs code points vs grapheme clusters
$samples = [
    ["ascii", "abc"],
    ["pre", "café"],
    ["decomp", "cafe\u{0301}"], // é decomposed: e + combining acute
    ["zwj", "a👨‍👩‍👧b"], // family emoji = 5 code points joined by ZWJ
];
foreach ($samples as [$label, $s]) {
    printf("%s: bytes=%d chars=%d graphemes=%d\n", $label, strlen($s), mb_strlen($s, "UTF-8"), grapheme_strlen($s));
}
Output
ascii: bytes=3 chars=3 graphemes=3
pre: bytes=5 chars=4 graphemes=4
decomp: bytes=6 chars=5 graphemes=4
zwj: bytes=20 chars=7 graphemes=3

Python v3.15.2

v3.15.2
# No grapheme segmentation in the stdlib — len() counts code points, so we
# hand-roll the simplified Grapheme_Cluster_Break rule (CR/LF/Extend/ZWJ)
def graphemes(s):
    count, prev = 0, -1
    for ch in s:
        cp = ord(ch)
        if 0x0300 <= cp <= 0x036F:       # Extend (combining marks): stay in the cluster
            continue
        if cp == 0x200D:                 # ZWJ: joiner stays in the cluster
            prev = cp
            continue
        if cp == 0x0A and prev == 0x0D:  # LF right after CR: one cluster
            prev = cp
            continue
        if prev == 0x200D:               # base char right after ZWJ: join the chain
            prev = cp
            continue
        count += 1
        prev = cp
    return count

for label, s in [("ascii", "abc"), ("pre", "café"), ("decomp", "cafe\u0301"), ("zwj", "a👨‍👩‍👧b")]:
    print(f"{label}: len={len(s)} graphemes={graphemes(s)}")
Output
ascii: len=3 graphemes=3
pre: len=4 graphemes=4
decomp: len=5 graphemes=4
zwj: len=7 graphemes=3

Rust v1.99.1

v1.99.1
use unicode_segmentation::UnicodeSegmentation;

fn main() {
    // std has no grapheme segmentation — unicode-segmentation's graphemes() is the norm
    for (label, s) in [
        ("ascii", "abc"),
        ("pre", "café"),
        ("decomp", "cafe\u{0301}"),
        ("zwj", "a👨‍👩‍👧b"),
    ] {
        println!("{}: chars={} graphemes={}", label, s.chars().count(), s.graphemes(true).count());
    }
}
Output
ascii: chars=3 graphemes=3
pre: chars=4 graphemes=4
decomp: chars=5 graphemes=4
zwj: chars=7 graphemes=3

TypeScript v26.13.1

v26.13.1
// Intl.Segmenter (ES2022, granularity "grapheme"): the native grapheme counter
const seg = new Intl.Segmenter("en", { granularity: "grapheme" });
const graphemes = (s: string): number => [...seg.segment(s)].length;
const samples: Array<[string, string]> = [["ascii", "abc"], ["pre", "café"], ["decomp", "cafe\u0301"], ["zwj", "a👨‍👩‍👧b"]];
for (const [label, s] of samples) {
  console.log(`${label}: codePoints=${[...s].length} graphemes=${graphemes(s)}`);
}
Output
ascii: codePoints=3 graphemes=3
pre: codePoints=4 graphemes=4
decomp: codePoints=5 graphemes=4
zwj: codePoints=7 graphemes=3

Language differences

The three-tier "length" comparison is the soul of this entry: strlen counts bytes (é takes 2 bytes in UTF-8), mb_strlen counts code points (precomposed é = 1, decomposed é = 2), and grapheme_strlen counts grapheme clusters (both é forms = 1, and the ZWJ family emoji counts as one) — only the third tier matches the user-perceived "one character". Pairs with the strlen/mb_strlen/grapheme_strrev entries as a family; requires the intl extension, and returns null/false on invalid UTF-8 (intl_get_error_code() exposes the ICU error).

C: no grapheme segmentation in the stdlib — the example hand-writes a UTF-8 decoder plus a simplified Grapheme_Cluster_Break (CR/LF/Extend/ZWJ only, enough for the demo strings); the full rule (Regional Indicators, emoji modifiers, Prepend, ...) needs ICU or libunistring.

C++: same idea as C (a std::string hand-written version in the example); reach for ICU BreakIterator in production.

C#: StringInfo.LengthInTextElements natively counts text elements (the ZWJ family counts as 1 in the example); note .Length is UTF-16 code units (chars=10 on the zwj line — the family emoji alone takes 8).

Go: no grapheme segmentation in the stdlib — the example shows the rune (code-point) count first, then adds the same simplified rule for the grapheme column; rivo/uniseg is the production choice.

Java: BreakIterator.getCharacterInstance "character boundaries" ≈ extended grapheme clusters (ZWJ family = 1 in the example); codePointCount is the code-point count; precision tracks the JDK-bundled Unicode version.

JavaScript: Intl.Segmenter (ES2022, granularity "grapheme") counts graphemes natively (ZWJ family = 1); [...s].length is the code-point count (surrogate pairs stay whole, but combining marks still split — see decomp: codePoints=5 vs graphemes=4).

PHP: one printf line shows all three tiers side by side; requires the intl extension; invalid UTF-8 returns null/false instead of throwing.

Python: no grapheme segmentation in the stdlib — len() counts code points (decomposed é = 2, ZWJ family = 7, both torn apart); the example hand-rolls the same simplified rule to get the right cluster count; in production use the third-party regex module's \X match or a grapheme library.

Rust: no grapheme segmentation in std — unicode-segmentation's graphemes(true) is the de facto standard (ZWJ family = 1 in the example); chars().count() is code points only.

TypeScript: same as JavaScript (Intl.Segmenter), plus type annotations.

Determinism: the four test strings are fixed (ASCII / precomposed é / decomposed é / ZWJ family) and deliberately contain only characters where every implementation agrees — the ICU family (PHP/JS/C#/Java), unicode-segmentation, and the hand-written simplified rule all produce identical counts on this sample, with no version-sensitive characters.