codePointAt returns the Unicode code point beginning at a specified UTF-16 char index. It avoids treating every char value as a complete character, which fails for supplementary characters encoded as surrogate pairs. section 6.1
Avoid charAt for Unicode-aware checks
A digit check based on charAt can reject a supplementary digit: static boolean startsWithDigit(String str) { return !str.isEmpty() && Character.isDigit(str.charAt(0)); } Use codePointAt instead: static boolean startsWithDigit(String str) { return !str.isEmpty() && Character.isDigit(str.codePointAt(0)); } The int result selects Character.isDigit(int), allowing digits outside the Basic Multilingual Plane. section 6.1
Use code-point-centered APIs when strings may contain arbitrary Unicode characters:
- Prefer codePointAt(), codePointBefore(), codePointCount(), and codePoints() over char-centered processing. section 6.1
- Account for the performance cost: locating the nth code point may require traversing earlier UTF-16 units to detect surrogate pairs. section 6.1
String part = string.codePoints().skip(rowNumber * rowLength)
.limit(rowLength)
.collect(StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append)
.toString();
Shows how to traverse code points and rebuild a string with appendCodePoint rather than slicing by char positions. section 6.1
