Java 字符串转 Unicode
在 Java 中,将字符串转换为 Unicode 表示有几种常见方法,以下是几种实现方式:

方法1:使用 String.codePointAt() 和 String.format()
public class StringToUnicode {
public static void main(String[] args) {
String str = "你好,世界!Hello World";
for (int i = 0; i < str.length(); i++) {
// 获取 Unicode 码点
int codePoint = str.codePointAt(i);
// 格式化为 \uXXXX 形式
String unicode = String.format("\\u%04x", codePoint);
System.out.print(unicode);
}
}
}
方法2:使用 Character.toString() 和 String.format()
public class StringToUnicode {
public static void main(String[] args) {
String str = "你好,世界!Hello World";
for (char c : str.toCharArray()) {
String unicode = String.format("\\u%04x", (int) c);
System.out.print(unicode);
}
}
}
方法3:处理 Unicode 代理对(surrogate pairs)
对于超出 BMP(基本多语言平面)的字符(如某些表情符号),需要特殊处理:
public class StringToUnicode {
public static void main(String[] args) {
String str = "😊 你好"; // 包含表情符号
for (int i = 0; i < str.length(); i++) {
int codePoint = str.codePointAt(i);
// 处理代理对
if (Character.isSupplementaryCodePoint(codePoint)) {
i++; // 跳过代理对的第二个字符
}
System.out.printf("\\u%04x ", codePoint);
}
}
}
方法4:转换为完整的 Unicode 转义序列
如果需要完整的 Unicode 转义序列(包括 \u 前缀):
public class StringToUnicode {
public static void main(String[] args) {
String str = "你好";
StringBuilder unicodeStr = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
unicodeStr.append(String.format("\\u%04x", (int) str.charAt(i)));
}
System.out.println(unicodeStr.toString()); // 输出: \u4f60\u597d
}
}
注意事项
codePointAt()方法能正确处理代理对(surrogate pairs),而charAt()可能会错误地处理某些 Unicode 字符- 对于 BMP 范围内的字符(U+0000 到 U+FFFF),可以直接使用
char类型 - 对于补充字符(U+10000 到 U+10FFFF),需要使用
int类型来存储码点 - Unicode 转义序列在 Java 字符串字面量中是有效的,可以直接用在代码中
反向操作:Unicode 转字符串
如果需要将 Unicode 转义序列转换回字符串:
public class UnicodeToString {
public static void main(String[] args) {
String unicodeStr = "\\u4f60\\u597d\\u4e16\\u754c";
// 使用正则表达式替换
String str = unicodeStr.replaceAll("\\\\u([0-9a-fA-F]{4})",
(match) -> String.valueOf((char) Integer.parseInt(match.group(1), 16)));
System.out.println(str); // 输出: 你好世界
}
}
