grapheme_strlen
grapheme_strlen(string $string): int|false|null
按字形簇(用户感知字符)计数:strlen 数字节、mb_strlen 数字符(码点)、grapheme_strlen 数字形——预组合 é 与分解 é 同为 1,ZWJ 家庭 emoji 整组算 1。
C C23
#include <stdio.h>
#include <string.h>
/* 解码一个 UTF-8 码点;返回其字节长度(输入结束时返回 0) */
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; /* 无效起始字节:消耗一个字节并替换为 U+FFFD */
}
/* 简化版 Grapheme_Cluster_Break:只处理 CR / LF / Extend / ZWJ——
足够覆盖本示例字符串(完整 UAX #29 需 ICU 或 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(组合字符):留在当前簇内 */
if (cp == 0x200D) { prev = cp; have_prev = 1; continue; } /* ZWJ:连接符留在当前簇内 */
if (have_prev && cp == 0x0A && prev == 0x0D) { prev = cp; continue; } /* CRLF 算一个簇 */
if (have_prev && prev == 0x200D) { prev = cp; continue; } /* ZWJ 后的基字符并入链中 */
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"}, /* 预组合 é(U+00E9) */
{"decomp", "cafe\xCC\x81"}, /* 分解 é: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;
}
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
#include <cstdio>
#include <string>
#include <utility>
// 解码一个 UTF-8 码点;返回其字节长度(输入结束时返回 0)
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;
}
// 简化版 Grapheme_Cluster_Break:只处理 CR / LF / Extend / ZWJ——
// 足够覆盖本示例字符串(完整 UAX #29 需 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:留在当前簇内
if (cp == 0x200D) { prev = cp; havePrev = 1; continue; } // ZWJ:连接符留在当前簇内
if (havePrev && cp == 0x0A && prev == 0x0D) { prev = cp; continue; } // CRLF 算一个簇
if (havePrev && prev == 0x200D) { prev = cp; continue; } // ZWJ 后的基字符并入链中
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"}, // 预组合 é(U+00E9)
{"decomp", "cafe\xCC\x81"}, // 分解 é: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;
}
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
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 按文本元素计数(≈ 字形簇)
Console.WriteLine($"{p[0]}: chars={p[1].Length} textElements={new StringInfo(p[1]).LengthInTextElements}");
}
ascii: chars=3 textElements=3 pre: chars=4 textElements=4 decomp: chars=5 textElements=4 zwj: chars=10 textElements=3
Go v1.27.4
package main
import (
"fmt"
"unicode/utf8"
)
// 标准库无字形切分——手写简化版
// Grapheme_Cluster_Break 规则:只处理 CR / LF / Extend / ZWJ
func graphemes(s string) int {
count, prev := 0, rune(0)
for _, r := range s { // range 把 UTF-8 解码成 rune(码点)
switch {
case r >= 0x0300 && r <= 0x036F: // Extend:留在当前簇内
case r == 0x200D: // ZWJ:连接符留在当前簇内
case r == 0x0A && prev == 0x0D: // CR 后的 LF:同一个簇
case prev == 0x200D: // ZWJ 后的基字符并入链中
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))
}
}
ascii: runes=3 graphemes=3 pre: runes=4 graphemes=4 decomp: runes=5 graphemes=4 zwj: runes=7 graphemes=3
Java v27.0.1
import java.text.BreakIterator;
public class Main {
// BreakIterator.getCharacterInstance 的「字符边界」≈ 字形簇
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]));
}
}
}
ascii: chars=3 graphemes=3 pre: chars=4 graphemes=4 decomp: chars=5 graphemes=4 zwj: chars=7 graphemes=3
JavaScript v26.13.1
// Intl.Segmenter(ES2022,granularity "grapheme"):原生字形计数器
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)}`);
}
ascii: codePoints=3 graphemes=3 pre: codePoints=4 graphemes=4 decomp: codePoints=5 graphemes=4 zwj: codePoints=7 graphemes=3
PHP v8.6.0
// 「长度」的三层:字节 vs 码点 vs 字形簇
$samples = [
["ascii", "abc"],
["pre", "café"],
["decomp", "cafe\u{0301}"], // 分解 é:e + 组合尖音符
["zwj", "a👨👩👧b"], // 家庭 emoji = 5 个码点经 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));
}
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
# 标准库无字形切分——len() 数的是码点,所以手写
# 简化版 Grapheme_Cluster_Break 规则(CR/LF/Extend/ZWJ)
def graphemes(s):
count, prev = 0, -1
for ch in s:
cp = ord(ch)
if 0x0300 <= cp <= 0x036F: # Extend(组合字符):留在当前簇内
continue
if cp == 0x200D: # ZWJ:连接符留在当前簇内
prev = cp
continue
if cp == 0x0A and prev == 0x0D: # CR 后的 LF:同一个簇
prev = cp
continue
if prev == 0x200D: # ZWJ 后的基字符并入链中
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)}")
ascii: len=3 graphemes=3 pre: len=4 graphemes=4 decomp: len=5 graphemes=4 zwj: len=7 graphemes=3
Rust v1.99.1
use unicode_segmentation::UnicodeSegmentation;
fn main() {
// std 无字形切分——unicode-segmentation 的 graphemes() 是事实标准
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());
}
}
ascii: chars=3 graphemes=3 pre: chars=4 graphemes=4 decomp: chars=5 graphemes=4 zwj: chars=7 graphemes=3
TypeScript v26.13.1
// Intl.Segmenter(ES2022,granularity "grapheme"):原生字形计数器
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)}`);
}
ascii: codePoints=3 graphemes=3 pre: codePoints=4 graphemes=4 decomp: codePoints=5 graphemes=4 zwj: codePoints=7 graphemes=3
语言差异说明
「长度」的三层对照是本条灵魂:strlen 数字节(UTF-8 下 é 占 2 字节)、mb_strlen 数字符/码点(预组合 é 计 1、分解 é 计 2)、grapheme_strlen 数字形簇(两种 é 都计 1,ZWJ 家庭 emoji 整组计 1)——只有第三层对应「用户感知的一个字」。与 strlen/mb_strlen/grapheme_strrev 条目构成家族联动;依赖 intl 扩展,非法 UTF-8 返回 null/false(intl_get_error_code() 可查 ICU 错误码)。
C:标准库无字形切分——示例手写 UTF-8 解码 + 简化版 Grapheme_Cluster_Break(只处理 CR/LF/Extend/ZWJ,足够覆盖演示串);完整规则(Regional Indicator、Emoji 修饰符、Prepend 等)需 ICU 或 libunistring。
C++:同 C 思路(示例为 std::string 版手写);生产环境直接用 ICU BreakIterator。
C#:StringInfo.LengthInTextElements 原生按「文本元素」计数(示例 ZWJ 家庭 emoji 计 1);注意 .Length 是 UTF-16 码元数(示例 zwj 行 chars=10,家庭 emoji 占 8 个码元)。
Go:标准库无字形切分——示例先以码点(runes)列计数,再手写同款简化规则补字形列;实战用 rivo/uniseg。
Java:BreakIterator.getCharacterInstance 的「字符边界」≈ 扩展字形簇(示例 ZWJ 家庭计 1);codePointCount 是码点数;精度跟随 JDK 内置 Unicode 版本。
JavaScript:Intl.Segmenter(ES2022,granularity "grapheme")原生字形计数(示例 ZWJ 家庭计 1);[...s].length 是码点数(代理对完整,但组合符仍被拆开,示例 decomp 行 codePoints=5 vs graphemes=4)。
PHP:printf 一行同时给三层数字,ez 对照;依赖 intl 扩展;输入非法 UTF-8 时返回 null/false 而非抛错。
Python:标准库无字形切分——len() 数码点(分解 é 计 2、ZWJ 家庭计 7,均被撕碎);示例手写同款简化规则给出正确字形数;生产用第三方 regex 模块的 \X 匹配或 grapheme 库。
Rust:std 无字形切分——unicode-segmentation crate 的 graphemes(true) 是事实标准(示例 ZWJ 家庭计 1);chars().count() 只是码点数。
TypeScript:同 JavaScript(Intl.Segmenter),仅补类型标注。
确定性论证:四个测试串固定(ASCII / 预组合 é / 分解 é / ZWJ 家庭),样本刻意只含各实现共同稳定的字符——ICU 系(PHP/JS/C#/Java)与 unicode-segmentation 及手写简化规则在样本上计数完全一致,无版本敏感字符。