java Unicode 与中文字符的转换

/**
  * 将字符转化为unicode码
  * @param s 待转化的字符串
  * @return 转化后的unicode码
  */
 public static String toUnicode(String s) {

  String s1 = "";

  for (int i = 0; i < s.length(); i++) {

   s1 += "\\u" + Integer.toHexString(s.charAt(i) & 0xffff);

  }

  return s1;

 }
 /**
  * 将unicode编码转化为字符串
  * @param str 待转化的字符串
  * @return 返回转化以后unicode编码
  */
 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;
 }

猜你喜欢

转载自blog.csdn.net/xujie9055/article/details/9271583
今日推荐