在 Java 中使用表情符号进行字符串编码?

Sha*_*haw 3 java encoding utf-8 utf-16

我有这样的小测试示例

    public class Main {
        public static void main(String[] args) {
            String s = "";
            System.out.println(s);
            System.out.println(s.length());
            System.out.println(s.toCharArray().length);
            System.out.println(s.getBytes(StandardCharsets.UTF_8).length);
            System.out.println(s.getBytes(StandardCharsets.UTF_16).length);
            System.out.println(s.codePointCount(0, s.length()));
            System.out.println(Character.codePointCount(s, 0, s.length()));
       }
    }
Run Code Online (Sandbox Code Playgroud)

结果是:


4
4
8
10
2
2
Run Code Online (Sandbox Code Playgroud)

我不明白,为什么 1 个 unicode 字符瓦努阿图标志返回 4 个长度,utf-8 中的 8 个字节和 utf-16 中的 10 个字节,我知道 java 使用 UTF-16 并且它需要 1 个字符(2 个字节)用于 1 个代码点但这让我对 1 个 unicode 字符的 4 个字符感到困惑,我认为它只需要 2 个字符但结果为 4。有人可以充分解释以帮助我理解这一点。非常感谢。

tha*_*guy 5

Unicode 标志表情符号被编码为两个代码点。

有 26 个区域指示符代表 AZ,一个标志是通过拼出 ISO 国家代码来编码的。例如,瓦努阿图国旗编码为“VU”,美国国旗编码为“US”。

指标都在补充平面,所以每个指标都需要两个UTF-16字符。这使char每个标志总共多达 4 个 Java 。

这样做的目的是避免在一个国家获得或失去独立时必须更新标准,并且它有助于 Unicode 联盟保持中立,因为它不必成为地缘政治主张的仲裁者。