Groovy String.offsetByCodePoints
Move by whole code points and return the resulting UTF-16 offset.
A simple example
String.offsetByCodePoints
- Start with "A😀B"
- Do this Advance two code points from the start
- Result At B
Syntax
public int offsetByCodePoints(int index, int codePointOffset)
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovyClip a badge at a whole symbol
A badge printer has room for a shortened name followed by an emoji. Choose the cut point by whole code points so the preview cannot include just half of a surrogate pair.
String note = "A😀Z"
println note.substring(0, note.offsetByCodePoints(0, 2))
A😀
The boundary falls after the complete emoji.
Find the offset of the last letter
A badge preview has room for only part of a Unicode label. Locate a whole-symbol boundary before slicing so a supplementary character is not split in the middle of its representation.
String note = "A😀Z"
println note.offsetByCodePoints(note.length(), -1)
3
The last letter starts at UTF-16 offset three.
Read a parcel sorting code
The depot scans a parcel marked NC-17. The scanner advances two code points from the beginning of the label. Which character starts at the resulting position?
What to watch for
The resulting offset can be used with substring. Moving beyond either end raises an exception.