Java字符串中的字符数 [英] Number of characters in Java String

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

问题描述

可能重复:
Java:使用unicode时的字符串长度覆盖以显示平方根?

Possible Duplicate:
Java: length of string when using unicode overline to display square roots?

如何获取字符串中的Unicode字符数?

How do I get number of Unicode characters in a String?

给出泰语字符char[]:

[อ, ภ, ิ, ช, า, ต, ิ]

这在String中显示为: อภิชาติ

This comes out in String as: อภิชาติ

String.length()返回7.我理解(技术上)有7个字符,但是我需要一种可以返回5的方法.这就是屏幕上显示的字符空间的确切数目.

String.length() returns 7. I understand there are (technically) 7 characters, but I need a method that would return me 5. That is the exact number of character spaces represented on screen.

推荐答案

似乎您只是不想将unicode标记算作单独的字符;

Seems you just want to not count the unicode marks as separate characters;

static boolean isMark(char ch)
{
    int type = Character.getType(ch);
    return type == Character.NON_SPACING_MARK ||
           type == Character.ENCLOSING_MARK ||
           type == Character.COMBINING_SPACING_MARK;
}

可以用作;

String olle = "อภิชาติ";
int count = 0;

for(int i=0; i<olle.length(); i++)
{
    if(!isMark(olle.charAt(i)))
        count++;
}

System.out.println(count);

并返回"5".

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

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