Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does java 8 String.chars() work properly with 8 byte chars?

Since java 8 String.chars() returns an IntStream, and the best answer I have found if you want a stream of chars is by casting i -> (char) i, I was wondering if anybody knows if this works properly with UTF-16 chars that actually take up 8 bytes?

like image 273
tumunu Avatar asked Sep 12 '26 20:09

tumunu


1 Answers

Depending on your definition of properly: No, it does not.

A Java char is a 16 bit UTF-16 code unit. Anything that is longer than that is represented as two char (as "surrogate pairs").

The same goes for String#length(). It will return the number of char, so your "long character" will count as two.

The reason that an IntStream is returned is just to not need to introduce a CharStream class. The data contained will still just be in the char 16-bit range.

However, there is .codePoints() in addition to chars(), which does return the 32-bit Unicode codepoints (also as an IntStream).

like image 61
Thilo Avatar answered Sep 15 '26 11:09

Thilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!