我正在努力获取unicode字符串的计数,并尝试了各种选项。看起来是个小问题,但影响很大。
在这里,我试图获得字符串str1的长度。我得到的是6。但实际上是3。将光标移动到字符串"குமார்“上也会显示为3个字符。
基本上,我想测量长度并打印每个字符。比如“கு”,“மா”,“ர்”。
public class one {
public static void main(String[] args) {
String str1 = new String("குமார்");
System.out.print(str1.length());
}
}
PS :这是泰米尔语。
发布于 2013-04-11 20:17:04
事实证明这真的很丑陋...我调试过你的字符串,它包含以下字符(以及它们的十六进制位置):
க0x0b95
ு0x0bc1
ம0x0bae
ா0x0bbe
ர0x0bb0
்0x0bcd
因此,泰米尔语显然使用类似变音符号的序列来获取所有字符,不幸的是,这些字符被视为单独的实体。
这不是UTF-8 / UTF-16的问题,因为它是泰米尔语Unicode编码中固有的问题。
建议的规范化程序不起作用,似乎泰米尔语已经被Unicode“专家”设计为显式地使用无法标准化的组合序列。啊哈。
我的下一个想法不是计算字符,而是字形,字符的视觉表示。
String str1 = new String(Normalizer.normalize("குமார்", Normalizer.Form.NFC ));
Font display = new Font("SansSerif",Font.PLAIN,12);
GlyphVector vec = display.createGlyphVector(new FontRenderContext(new AffineTransform(),false, false),str1);
System.out.println(vec.getNumGlyphs());
for (int i=0; i<str1.length(); i++)
System.out.printf("%s %s %s %n",str1.charAt(i),Integer.toHexString((int) str1.charAt(i)),vec.getGlyphVisualBounds(i).getBounds2D().toString());
结果是:
b95 x=0.0,y=-6.0,w=7.0,h=6.0,க
bc1 x=8.0,y=-6.0,w=7.0,h=4.0,ு
bae x=17.0,y=-6.0,w=6.0,h=6.0,ம
bbe x=23.0,y=-6.0,w=5.0,h=6.0,ா
bb0 x=30.0,y=-6.0,w=4.0,h=8.0,ர
bcd x=31.0,y=-9.0,w=1.0,h=2.0,்
由于字形是相交的,您需要像在其他解决方案中一样使用Java字符类型函数。
解决方案:
我正在使用这个链接:http://www.venkatarangan.com/blog/content/binary/Counting%20Letters%20in%20an%20Unicode%20String.pdf
public static int getTamilStringLength(String tamil) {
int dependentCharacterLength = 0;
for (int index = 0; index < tamil.length(); index++) {
char code = tamil.charAt(index);
if (code == 0xB82)
dependentCharacterLength++;
else if (code >= 0x0BBE && code <= 0x0BC8)
dependentCharacterLength++;
else if (code >= 0x0BCA && code <= 0x0BD7)
dependentCharacterLength++;
}
return tamil.length() - dependentCharacterLength;
}
您需要排除组合字符并相应地对其进行计数。
发布于 2013-04-11 20:51:31
如前所述,您的字符串包含6个不同的代码点。其中一半是字母,另一半是元音符号。(组合标记)
您可以使用ICU4J库中内置的transformations,使用以下规则删除所有非字母的元音符号:
:^Letter:删除
并对结果字符串进行计数。在他们的演示站点上试用一下:
http://demo.icu-project.org/icu-bin/translit
我不会将结果字符串显示给最终用户,而且我也不是专家,因此可能需要调整规则以达到一般情况,但这只是一种想法。
发布于 2018-11-29 05:21:44
这是一种计算Java字符串长度的新方法,其中考虑了Unicode字符。
int unicodeLength = str.codePointCount(0, str.length);
https://stackoverflow.com/questions/15947992
复制相似问题