BreakIterator Grapheme Clusters For Emoji
BreakIterator.getCharacterInstance splits text into user-perceived grapheme clusters: a ZWJ-joined emoji family is one character despite many code points.
Code
import java.text.BreakIterator;
import java.util.Locale;
public class GraphemeClusters {
public static void main(String[] args) {
String status = "ok👨👩👧👦!";
BreakIterator clusters = BreakIterator.getCharacterInstance(Locale.ROOT);
clusters.setText(status);
// 现代 JDK 的字形簇规则(UAX #29)把 ZWJ 连接的 emoji 家族算作一个字符
int start = clusters.first();
int count = 0;
for (int end = clusters.next(); end != BreakIterator.DONE; end = clusters.next()) {
System.out.println("cluster " + count + ": " + status.substring(start, end));
count++;
start = end;
}
// 同一段文本的三种"长度"各不相同:UTF-16 单元 > 码点 > 字形簇
System.out.println("utf16 units: " + status.length());
System.out.println("code points: " + status.codePointCount(0, status.length()));
System.out.println("graphemes: " + count);
}
}How it works
BreakIterator Grapheme Clusters For Emoji comes down to the class GraphemeClusters and the function main.
Repetition is confined to for (int end = clusters.next(); end != BreakIterator.DONE; end = clusters.next()) — the rest of the file is straight-line.
Points of care
- Runs with what the toolchain already gives you — nothing extra.
Putting it to use
The primary signature is public static void main(String[] args)
The run emits 4 labeled sections — cluster, utf16 units:, code points:, graphemes: — one per step.
Core lines
BreakIterator clusters = BreakIterator.getCharacterInstance(Locale.ROOT);
String status = "ok👨👩👧👦!";
int start = clusters.first();
Interactive Tools for This Topic
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Text ReverserReverse text by characters, words, or lines, counting Unicode code points so emoji stay intact.
FAQ
- What does BreakIterator Grapheme Clusters For Emoji print when run?
- Run it as a complete program — the output lines carry labels such as `cluster`, `utf16 units:`, `code points:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.