1. 程式人生 > >Unicode和漢字的相互轉化

Unicode和漢字的相互轉化

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Unicode{
public Unicode() {
}

public static void main(String[] args) {
String str = "哈哈";
String str1 = StringToUnicode(str);
System.out.println(str1);
String str2="\u54c8\u54c8";
System.out.println(str2);
}

public static String StringToUnicode(String str) {
StringBuffer strb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
strb.append("\\u").append(Integer.toHexString(str.charAt(i)));
}
return strb.toString();
}

public static String UnicodeToString(String str) {
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
Matcher matcher = pattern.matcher(str);
char ch;
while (matcher.find()) {
ch = (char) Integer.parseInt(matcher.group(2), 16);
str = str.replace(matcher.group(1), ch + "");
}
return str;
}
}