package com.yt17lu.commons;
import java.util.Scanner;
public class UnicodeParse {
/**
*
* @param dataStr
* 接受的unicode 字符串
* @return 代表的字符串
* @throws 如果输入的格式不是u后跟2-4位16进制则抛出格式错误
*/
public static String parse(String dataStr) {
boolean matches = dataStr.matches("^(\\\\u\\p{XDigit}{2,4})*$");
if (!matches) {
throw new RuntimeException(dataStr + ",unicode字符串格式错误");
}
int start = 0;
int end = 0;
StringBuffer buffer = new StringBuffer();
int len = dataStr.length();
while (start < len) {
end = dataStr.indexOf("\\u", start + 2);
end = (end == -1) ? len : end;
String temp = dataStr.substring(start + 2, end);
buffer.append((char) Integer.parseInt(temp, 16));
start = end;
}
return buffer.toString();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入字符:");
String code = input.next();
System.out.println(UnicodeParse.parse(code));
}
}
unicode 字符串转 表达的字符
最新推荐文章于 2025-11-26 15:59:01 发布
本文提供了一个Java方法,用于解析Unicode字符串,并将其转换为实际的字符串。通过使用正则表达式和Integer.parseInt()方法,该实现能够正确处理u后跟2-4位16进制数的Unicode字符串。此外,提供了命令行交互示例来演示如何使用此方法。
1440

被折叠的 条评论
为什么被折叠?



