Java 编码-代码点计数和长度之间的不同结果

Java 编码-代码点计数和长度之间的不同结果,java,encoding,Java,Encoding,我发现了一个棘手的地方,却找不到任何答案来解释为什么会发生这种情况 主要问题是字符串的长度 它是否包含一个或两个字符 代码: public class App { public static void main(String[] args) throws Exception { char ch0 = 55378; char ch1 = 56816; String str = new String(new char[]{ch0, ch1});

我发现了一个棘手的地方,却找不到任何答案来解释为什么会发生这种情况

主要问题是字符串的长度

它是否包含一个或两个字符

代码:

public class App {
    public static void main(String[] args) throws Exception {
        char ch0 = 55378;
        char ch1 = 56816;
        String str = new String(new char[]{ch0, ch1});
        System.out.println(str);
        System.out.println(str.length());
        System.out.println(str.codePointCount(0, 2));
        System.out.println(str.charAt(0));
        System.out.println(str.charAt(1));
    }
}
?
2
1
?
?
输出:

public class App {
    public static void main(String[] args) throws Exception {
        char ch0 = 55378;
        char ch1 = 56816;
        String str = new String(new char[]{ch0, ch1});
        System.out.println(str);
        System.out.println(str.length());
        System.out.println(str.codePointCount(0, 2));
        System.out.println(str.charAt(0));
        System.out.println(str.charAt(1));
    }
}
?
2
1
?
?
有什么建议吗

它是否包含一个或两个字符

它包含一个Unicode字符,由2个UTF-16代码单元组成。Java中的每个
char
都是一个UTF-16代码单元。。。它可能不是一个完整的角色。每个字符都有一个代码点-Unicode提供了一个编码字符集,将每个字符映射到表示该字符的整数(代码点)

length()
返回代码单元数,而
codePointCount
返回代码点数


您可能想看看我的文章-术语都翻译得很好(因为它是标准术语),所以请忽略.NET特定部分。

我建议您花点时间看看您希望得到什么样的输出?这正是我想要的