如何将 Unicode 字符放入 Java 字符串中?

Yee*_*ezh 0 java string unicode char

如何将 Unicode char U+1F604 放入 Java String?我尝试使用

String s = "\u1F604";
Run Code Online (Sandbox Code Playgroud)

但它相当于

String s = "\u1F60"+"4";
Run Code Online (Sandbox Code Playgroud)

它被分成2个字符。

Hyp*_*ino 7

DuncG 的回答是一个很好的方法。对此的简短解释是,默认情况下 Unicode 字符仅占用 4 个字节,因此字符串文字转义只允许\u####. 然而,表情符号是代理对和Unicode已预留U+D800U+DFFF这些对,允许1024×1024对字符。

另一种不需要转换为 UTF-16 并编码为代理对的不同方法是使用Character.toChars(...)

public class Main {
	public static void main(String[] args) {
		String s = "Hello " + new String(Character.toChars(0x1f604)) + "!";
		System.out.println(s);
	}
}
Run Code Online (Sandbox Code Playgroud)

在线试试吧!


Joo*_*gen 5

第三种变体,尤其是Character.toString(0x1f604)

public class Main {
  public static void main(String[] args) {
    String s1 = "Hello " + Character.toString(0x1f604) + "!"; // Since Java 11
    String s2 = "Hello " + new String(new int[]{0x1f604}, 0, 1) + "!"; // < 11
    System.out.println(s1 + " " + s2);
  }
}
Run Code Online (Sandbox Code Playgroud)

(注意在其他一些语言中\U0001f604可能会用到。在java中\u\U是一样的。)