String.codePoints()
Returns a stream of Unicode code points. Unlike chars(), an emoji counts as one character.
Available since: Java 9
Syntax
public IntStream codePoints()Return value
IntStreamAn IntStream with the code of each character.
Examples
length() counts char units, while codePoints() counts real characters:
void main() {
String text = "Hi😀";
IO.println(text.length());
IO.println(text.codePoints().count());
IO.println(text.codePointCount(0, text.length()));
}Output:
4
3
3Each character and its code as U+XXXX:
void main() {
"A€😀".codePoints().forEach(cp ->
IO.println(Character.toString(cp) + " U+" + Integer.toHexString(cp).toUpperCase()));
}Output:
A U+41
€ U+20AC
😀 U+1F600Notes
A char holds 16 bits, and characters outside Unicode's basic plane (emoji, rare ideographs) take two char values — a surrogate pair. chars() yields those halves separately, codePoints() yields the whole character. Turn a code back into a string with Character.toString(cp) or new StringBuilder().appendCodePoint(cp). codePointAt(i) returns the code of the character starting at index i.
See also
- String.chars() — Returns a stream of the character codes of a string.
- String.length() — Returns the number of characters in a string.
- Character.isDigit() — Checks whether a character is a digit. Related checks are isLetter(), isWhitespace(), isUpperCase().
- StringBuilder.reverse() — Reverses the contents of a StringBuilder.
In the tutorial
- String methods — The main String methods in Java: searching, substring, changing case, strip, replace, split, join, repeat and string checks.