Java字符串中的字符数

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

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

鉴于泰国字符的char[]

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

这在String中出现:อภิชาติ

String.length()返回7.我知道(技术上)有7个字符,但是我需要一个能够返回5的方法。这就是屏幕上显示的字符空间的确切数量。

似乎你只是想不将unicode标记统计为单独的字符;

 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 

并返回'5'。

您可以在此处调整发布到此问题的解决方案:

Java中的Unicode到字符串转换

通过剥离’#’字符并计算字符串中的剩余字符。

您可以使用java.text.BreakIterator来查找字形之间的间隙(“可视字符”)并对它们进行计数。 这是一个例子:

 import java.text.BreakIterator; .. int graphemeLength(String str) { BreakIterator iter = BreakIterator.getCharacterInstance(); iter.setText(str); int count = 0; while (iter.next() != BreakIterator.DONE) count++; return count; } 

现在graphemeLength("อภิชาติ")将返回5。