java Unicode与中文互换

来源:互联网 发布:淘宝寄快递在哪里 编辑:程序博客网 时间:2024/06/18 13:48

原文:http://blog.csdn.net/roserose0002/article/details/6972391

static String string2Unicode(String s) {
    try {
      StringBuffer out = new StringBuffer("");
      byte[] bytes = s.getBytes("unicode");
      for (int i = 2; i < bytes.length - 1; i += 2) {
        out.append("u");
        String str = Integer.toHexString(bytes[i + 1] & 0xff);
        for (int j = str.length(); j < 2; j++) {
          out.append("0");
        }
        String str1 = Integer.toHexString(bytes[i] & 0xff);

        out.append(str);
        out.append(str1);
        out.append(" ");
      }
      return out.toString().toUpperCase();
    }
    catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      return null;
    }
  } 

 

static String unicode2String(String unicodeStr){
    StringBuffer sb = new StringBuffer();
    String str[] = unicodeStr.toUpperCase().split("U");
    for(int i=0;i<str.length;i++){
      if(str[i].equals("")) continue;
      char c = (char)Integer.parseInt(str[i].trim(),16);
      sb.append(c);
    }
    return sb.toString();
  }

    System.out.println(string2Unicode("中文测试ABC"));
    System.out.println(unicode2String(string2Unicode("中文测试ABC")));


0 0