getGraphemeLengthAt static method
Calculates the number of UTF-16 code units to delete starting from offset
to delete one complete grapheme cluster. Returns 1 for regular characters,
2 for surrogate pairs (emoji), and potentially more for complex clusters
(e.g., CJK + variation selector, ZWJ sequences).
Implementation
static int getGraphemeLengthAt(String s, int offset) {
if (offset < 0 || offset >= s.length) return 1;
// Walk the grapheme clusters to find the one starting at [offset]
int pos = 0;
for (final grapheme in s.characters) {
if (pos == offset) {
return grapheme.length;
}
pos += grapheme.length;
if (pos > offset) {
// offset falls inside a grapheme cluster — return the remaining length
return pos - offset;
}
}
return 1;
}