In Java, Character.offsetByCodePoints(seq, index, codePointOffset) starts at char index index and moves by codePointOffsetcode points, returning the new char index. A positive offset moves forward, a negative offset moves backward, and a surrogate pair always counts as one step.
It answers questions such as "where does the third character end?" so that you can call substring without cutting an emoji in half. The char array overload limits the search to a sub-array given by start and count.
A static method of java.lang.Character (Java 5+): call it on the class, as in Character.offsetByCodePoints(...); you do not need a Character object. No import is needed, because java.lang is always available.
Syntax
Pass the text, a start index, and how many code points to move.
Java
String s = "A\uD83D\uDE00B"; // 4 chars, 3 code points
int i1 = Character.offsetByCodePoints(s, 0, 1); // 1
int i2 = Character.offsetByCodePoints(s, 0, 2); // 3 (jumped over the pair)
int i3 = Character.offsetByCodePoints(s, 4, -2); // 1 (moving backward)
Array form: offsetByCodePoints(char[] a, int start, int count, int index, int codePointOffset), where start and count describe the part of the array that may be used and the result is an index into a.
Library declarations
Java
// java.lang.Character (since Java 5)
public static int offsetByCodePoints(CharSequence seq, int index, int codePointOffset)
public static int offsetByCodePoints(char[] a, int start, int count, int index, int codePointOffset)
Parameters
Parameter
Description
seq / a
The text. Must not be null.
index (int)
The char index to start from, 0 to the length.
codePointOffset (int)
How many code points to move; negative moves backward.
start, count
Array overload only: the usable sub-array.
Return Value
Return Value
Description
int
The char index reached after moving codePointOffset code points.