找出Java / Android中UTF-8字符串中的字符数 [英] Find out number of characters in a UTF-8 string in Java/Android

查看:134
本文介绍了找出Java / Android中UTF-8字符串中的字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当字符串以UTF-8存储时,我试图找出字符串长度。
我尝试了以下方法:

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.

我找到了一个显示UTF-8字符串长度和字节长度的网站。
https://mothereff.in/byte-counter
让我们说我的字符串是मेरानाम,然后我应该得到8个字符而不是22个字节的字符串长度。

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

任何人都可以请指导。

推荐答案

只需将程序保存为 utf-8
并执行以下操作

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

        String str= "मेरा नाम";
        System.out.println(str.length());

o / p = 8

o/p = 8

这篇关于找出Java / Android中UTF-8字符串中的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆