Sujit Devkar Sujit Devkar - 1 year ago 87
Java Question

Find out number of characters in a UTF-8 string in Java/Android

I am trying to find out a string length when the string is stored in UTF-8.
I tried following approach:

String str = "मेरा नाम";
Charset UTF8_CHARSET = Charset.forName("UTF-8");
byte[] abc = str.getBytes(UTF8_CHARSET);
int length = abc.length;

This gives me length of the byte array, but not number of characters in the string.

I found a website which shows both UTF-8 string length and byte length.
Let's say my string is मेरा नाम, then I should get string length as 8 characters and not 22 bytes.

Could anyone please guide on this.

Answer Source

simply you save your program as utf-8 and do as below

        String str= "मेरा नाम";

o/p = 8

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download