Alfredo Osorio
Alfredo Osorio

Reputation: 11475

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.

Upvotes: 5

Views: 835

Answers (1)

Use:

string.codePointCount(0, string.length())

Upvotes: 9

Related Questions