简体   繁体   中英

Different count for String.length() for different languages

What I want

Given a String s and a coordinate x1, want to print to pdf considering x1 at the center. I need starting x-coordinate

problem

I can easily calculate start coordinate(x) with x1-s.length()/2 to a position it at the center but it fails for Hindi(Language)

How to count the actual no of characters ignoring the Unicode characters but the letters. I basically want to print the string at the center, String is variable

There are a couple of reasons why the length method might get you an unexpected answer.

The length method on String returns the number of char values in the string, but there are more Unicode characters than possible char values, so for some characters more than one char value is used to store the character. To get the length you expect for, try this: s.codePointCount(0, s.length())

If your string contains a Combining Diacritical Mark , that uses one char, but is displayed combined with another character. Here's a question about how to spot those: detect any combining character in Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM