Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Total characters (not code units) of a String in Java considering Supplementary Characters

How can you obtain the total characters of a String, considering that it could have supplementary characters which takes 2 code units to be encoded.

Example:

String strTest = "a𐐀"; //Supplementary character
System.out.println(strTest.length());

Output:

3

As we can see if we use length() we obtain 3 instead of 2. What I want to obtain is the number of characters for a given String, not the number of code units.

like image 284
Alfredo Osorio Avatar asked Jan 19 '23 16:01

Alfredo Osorio


1 Answers

Use:

string.codePointCount(0, string.length())
like image 130
Christoffer Hammarström Avatar answered Jan 30 '23 08:01

Christoffer Hammarström