Library contents

Java 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.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("A😀B".offsetByCodePoints(0, 2));
    }
}
Output
3

Syntax

Java syntax
public int offsetByCodePoints(int index, int codePointOffset)
JDK 21 method signatures (1)
public int offsetByCodePoints(int index, int codePointOffset)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Take two symbols for a badge preview

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 badge = "A😀Z"
ResultA😀
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String badge = "A😀Z";
        System.out.println(badge.substring(0, badge.offsetByCodePoints(0, 2)));
    }
}
Output
A😀

The ending offset falls after the whole emoji.

Advertisements

Remove the final status symbol

A message ends with a status symbol that may use more than one encoding unit. Find the symbol's starting boundary before removing it so the remainder stays valid text.

From the programString status = "paid✅"
Resultpaid
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String status = "paid✅";
        System.out.println(status.substring(0, status.offsetByCodePoints(status.length(), -1)));
    }
}
Output
paid

Stepping back one code point finds where the suffix begins.

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