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;
	}
}
 

猜你喜欢

转载自104zz.iteye.com/blog/1694301