Library contents

Groovy String.offsetByCodePoints

Move by whole code points and return the resulting UTF-16 offset.

A simple example

String.offsetByCodePoints

  1. Start with "A😀B"
  2. Do this Advance two code points from the start
  3. Result At B
A uses one UTF-16 unit and the emoji uses two. The next code point starts at unit offset 3.

Syntax

Groovy 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.groovy

Clip 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.

From the programString note = "A😀Z"
ResultA😀
Lesson.groovy
String note = "A😀Z"
println note.substring(0, note.offsetByCodePoints(0, 2))
Output
A😀

The boundary falls after the complete emoji.

Advertisements

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.

From the programString note = "A😀Z"
Result3
Lesson.groovy
String note = "A😀Z"
println note.offsetByCodePoints(note.length(), -1)
Output
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?

GivenNC-17
Worked result-

What to watch for

The resulting offset can be used with substring. Moving beyond either end raises an exception.

Documentation for String.offsetByCodePoints