【问题标题】:Java Why is the length of the string twice 36 while it contains just 18 characters?Java 为什么字符串的长度是 36 的两倍,而它只包含 18 个字符?
【发布时间】:2014-12-13 16:49:50
【问题描述】:

以下字符串 st 仅包含 18 个字符,但当我打印它的长度时,它显示为 36 它的两倍。

String st = "????????????????????????????????????????????????????????????????????????";
System.out.println(st.length());

注意:该字符串包含我将在我的聊天应用程序中使用的符号,长度可能因 16 位和 8 位字符而异,但我对此感到模糊。

【问题讨论】:

    标签: java string character-encoding string-length


    【解决方案1】:

    根据 JavaDocs:http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#length()

    Returns the length of this string. 
    The length is equal to the number of Unicode code units in the string.
    

    如果您有需要多个字节的 Unicode 字符,则 length() 返回总字节数,而不是实际字符数。

    【讨论】:

    • 另外,如果您对查找视觉长度感兴趣,可以使用str.codePointCount(0, str.length()) - 请参阅this related question
    • 不是字节长度,而是形成字符所需的码点数。 Java 使用 utf16 无法编码所有字符,因此它对某些字符使用代理对。
    猜你喜欢
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多