有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在上获得正确的字符数。NET、Java和Sql Server?(请在谷歌浏览器中阅读此内容)

考虑到这个字符串

HELLO𝄞水

图例:http://en.wikipedia.org/wiki/UTF-16

𝄞 is 4 bytes
水 is 2 bytes

Postgresql数据库(UTF-8)返回正确的长度7:

select length('HELLO𝄞水');

我都注意到了。NET和Java返回8:

Console.WriteLine("HELLO𝄞水");

System.out.println("HELLO𝄞水");

Sql Server也返回8:

SELECT LEN('HELLO𝄞水');

。NET、Java和Sql Server返回正确的字符串长度当给定的unicode字符不是可变长度时,它们都返回6:

  HELLO水

对于可变长度的,返回7,这是不正确的:

  HELLO𝄞

。NET、Java和Sql Server使用UTF-16。似乎他们计算UTF-16字符串长度的实现被破坏了。或者这是UTF-16规定的?UTF-16作为其UTF-8近亲具有可变长度能力。但是为什么是UTF-16(或者说是.NET、Java、SQL Server等等的错?)无法像UTF-8那样正确计算字符串的长度


Python返回的长度为12,但我不知道如何解释它返回12的原因。这可能完全是另一个话题,我离题了

len("HELLO𝄞水")

问题是,如何获得正确的字符计数。NET、Java和Sql Server?如果函数返回不正确的字符计数,则很难实现下一个twitter

如果我可以补充的话,我无法使用Firefox发布这篇文章。我在谷歌浏览器上发布了这个问题。Firefox无法显示可变长度的Unicode


共 (3) 个答案

  1. # 1 楼答案

    C#(可能还有SQL和Java)返回字符串中的字符元素数

    String.Length

    The Length property returns the number of Char objects in this instance, not the number of Unicode characters. The reason is that a Unicode character might be represented by more than one Char. Use the System.Globalization.StringInfo class to work with each Unicode character instead of each Char.

  2. # 2 楼答案

    在Java中:

    String s = "HELLO𝄞水";
    System.out.println(s.codePointCount(0, s.length())); // 7
    System.out.println(s.length()); // 8
    
  3. # 3 楼答案

    。网络:String.Length Property

    The Length property returns the number of Char objects in this instance, not the number of Unicode characters. The reason is that a Unicode character might be represented by more than one Char. Use the System.Globalization.StringInfo class to work with each Unicode character instead of each Char.

    所以我们应该使用StringInfo类来获得Unicode字符的正确计数

    String s = "HELLO𝄞水";
    Console.WriteLine (s);
    Console.WriteLine ("Count of char: {0:d}", s.Length);
    
    StringInfo info = new StringInfo (s);
    Console.WriteLine ("Count of Unicode characters: {0:d}", info.LengthInTextElements);
    

    输出:

    HELLO𝄞水
    Count of char: 8
    Count of Unicode characters: 7