杰瑞科技汇

Java字符如何转Unicode?

方法 1:使用 int 获取 Unicode 码点

每个字符在 Java 中都有一个对应的 Unicode 码点(整数),可以通过强制类型转换获取:

char ch = '中';
int codePoint = (int) ch; // 获取 Unicode 码点
System.out.println("字符 '" + ch + "' 的 Unicode 码点是: " + codePoint);
// 输出: 字符 '中' 的 Unicode 码点是: 20013

方法 2:使用 Character.codePointAt()

对于字符串中的字符,可以使用 Character.codePointAt() 获取其 Unicode 码点:

String str = "Hello";
int codePoint = Character.codePointAt(str, 0); // 获取第一个字符的码点
System.out.println("字符 '" + str.charAt(0) + "' 的 Unicode 码点是: " + codePoint);
// 输出: 字符 'H' 的 Unicode 码点是: 72

方法 3:格式化输出 Unicode 转义序列

如果需要将字符表示为 \uXXXX 格式的 Unicode 转义序列(如 \u4e2d 表示 '中'),可以使用以下方法:

手动转换

char ch = '中';
String unicodeEscaped = String.format("\\u%04x", (int) ch);
System.out.println("字符 '" + ch + "' 的 Unicode 转义序列是: " + unicodeEscaped);
// 输出: 字符 '中' 的 Unicode 转义序列是: \u4e2d

自动转换(字符串转 Unicode 转义序列)

String str = "Hello世界";
StringBuilder unicodeStr = new StringBuilder();
for (char ch : str.toCharArray()) {
    unicodeStr.append(String.format("\\u%04x", (int) ch));
}
System.out.println("字符串的 Unicode 转义序列是: " + unicodeStr);
// 输出: 字符串的 Unicode 转义序列是: \u0048\u0065\u006c\u006c\u006f\u4e16\u754c

方法 4:反向转换(Unicode 转义序列 → 字符)

如果有一个 Unicode 转义序列(如 \u4e2d),可以通过以下方式还原为字符:

String unicodeEscaped = "\\u4e2d"; // 注意:需要双反斜杠表示字符串中的 \
char ch = (char) Integer.parseInt(unicodeEscaped.substring(2), 16);
System.out.println("Unicode 转义序列 '" + unicodeEscaped + "' 对应的字符是: " + ch);
// 输出: Unicode 转义序列 '\u4e2d' 对应的字符是: 中

需求 方法 示例
获取字符的 Unicode 码点 (int) chCharacter.codePointAt() (int) '中'20013
生成 Unicode 转义序列 String.format("\\u%04x", (int) ch) '中'\u4e2d
从 Unicode 转义序列还原字符 Integer.parseInt(..., 16) \u4e2d'中'

根据实际需求选择合适的方法即可!

分享:
扫描分享到社交APP
上一篇
下一篇