Java 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
class Main {
public static void main(String[] args) throws Exception {
System.out.println("A😀B".offsetByCodePoints(0, 2));
}
}
3
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.javaTake 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.
class Main {
public static void main(String[] args) throws Exception {
String badge = "A😀Z";
System.out.println(badge.substring(0, badge.offsetByCodePoints(0, 2)));
}
}
A😀
The ending offset falls after the whole emoji.
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.
class Main {
public static void main(String[] args) throws Exception {
String status = "paid✅";
System.out.println(status.substring(0, status.offsetByCodePoints(status.length(), -1)));
}
}
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?
What to watch for
The resulting offset can be used with substring. Moving beyond either end raises an exception.