繁體中文
字串索引:Code unit、Code point、Grapheme
「字串長度」至少有三種合理答案,加上 byte 數就是四種:
- Code unit:編碼的最小單位。UTF-8 是 1 byte、UTF-16 是 2 bytes、UTF-32 是 4 bytes。
- Code point:Unicode 編號的數量。
- Grapheme cluster:使用者看到的「字」的數量。
| 字串 | UTF-8 bytes | UTF-16 units | Code points | Graphemes |
|---|---|---|---|---|
| abc | 3 | 3 | 3 | 3 |
| 中文 | 6 | 2 | 2 | 2 |
| 😀 | 4 | 2 | 1 | 1 |
| é(e + U+0301) | 3 | 2 | 2 | 1 |
| 🇹🇼 | 8 | 4 | 2 | 1 |
| 👨👩👧 | 18 | 8 | 5 | 1 |
18
UTF-8 bytes
8
UTF-16 code units(JS .length)
5
Code points
1
Graphemes
Grapheme(虛線框)→ code point · 滑鼠移到任一格,會標出同一個 code point 對應的所有 code unit
👨U+1F468ZWJU+200D👩U+1F469ZWJU+200D👧U+1F467
各語言的「長度」是什麼?
| 語言 | 預設 length | 單位 | 👨👩👧 |
|---|---|---|---|
| JavaScript / Java / C# | s.length | UTF-16 code unit | 8 |
| Python 3 | len(s) | Code point | 5 |
| Go / Rust | len(s) / s.len() | UTF-8 byte | 18 |
| Swift | s.count | Grapheme cluster | 1 |
各語言的「字元」型別細節見 「字元」型別。
實務建議
- 儲存、傳輸、計算 buffer 大小 → 用 byte(code unit)。
- 游標移動、截斷顯示文字、計算「幾個字」→ 用 grapheme(JS 的
Intl.Segmenter、Rust 的unicode-segmentation、Python 的regex模組\X)。 - Code point 索引是 O(n)(除非用 UTF-32),且依然會把 é 切成兩半,幾乎不是你要的。
- JS 的
for...of、Array.from(s)、[...s]以 code point 迭代;s[i]、s.length以 code unit。