CKTIS / Java
String.codePointBefore — code point before an index
String.codePointBefore returns the Unicode value before a UTF-16 code-unit index, accounting for surrogate pairs.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
public int codePointBefore(int index)String.codePointBefore(int index) returns an int representing the code point before index. The index counts UTF-16 code units (char), not code points; its valid range is 1 <= index && index <= length().
A low surrogate immediately before the index combines with a preceding high surrogate. Otherwise, the method returns the single char value, including a surrogate. An index inside a pair is not automatically corrected.
Outside that range, it throws IndexOutOfBoundsException; an empty string has no valid index. In the example, codePointBefore(3) returns 128512, whereas codePointBefore(2) returns the high surrogate 55357.
Examples
public class Main {
public static void main(String[] args) {
String text = "A\uD83D\uDE00B";
System.out.println(text.length());
System.out.println(text.codePointBefore(3));
System.out.println(text.codePointBefore(2));
System.out.println(text.codePointBefore(1));
}
}Result
4 128512 55357 65
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.