在Java中,你可以使用内置的类和方法来处理Unicode编码的转换
public class UnicodeConverter {
public static void main(String[] args) {
String input = "Hello, 世界!";
String unicode = toUnicode(input);
System.out.println("Unicode: " + unicode);
}
public static String toUnicode(String input) {
StringBuilder builder = new StringBuilder();
for (char ch : input.toCharArray()) {
builder.append(String.format("\\u%04x", (int) ch));
}
return builder.toString();
}
}
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UnicodeConverter {
public static void main(String[] args) {
String unicode = "Hello, \\u4e16\\u754c!";
String output = fromUnicode(unicode);
System.out.println("Output: " + output);
}
public static String fromUnicode(String unicode) {
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
Matcher matcher = pattern.matcher(unicode);
char ch;
while (matcher.find()) {
ch = (char) Integer.parseInt(matcher.group(2), 16);
unicode = unicode.replace(matcher.group(1), ch + "");
}
return unicode;
}
}
这两个示例分别演示了如何将字符串转换为Unicode编码以及如何将Unicode编码转换回字符串。你可以根据需要修改这些代码以适应你的项目。