现在的位置: 首页 > 综合 > 正文

unicode与汉字之间的转换

2018年05月05日 ⁄ 综合 ⁄ 共 873字 ⁄ 字号 评论关闭
/**
     * 中文转unicode
     * @param  str
     * @return unicode
     */
public String  chineseToUnicode(String str)
    {
        String result = "";
        for (int i = 0; i < str.length(); i++)
        {
            int chr1 = (char) str.charAt(i);
            result  += "\\u" + Integer.toHexString(chr1);            
        }
        return result;
    }
/**
     * unicode转中文
     * @param  str
     * @return 中文
     */
     public static String UnicodeTochinese(String dataStr) {
         int index = 0;
         StringBuffer buffer = new StringBuffer();
   
         while(index<dataStr.length()) {
                if(!"\\u".equals(dataStr.substring(index,index+2))){
                 buffer.append(dataStr.charAt(index));
                 index++;
                 continue;
          }
         String charStr = "";
         charStr = dataStr.substring(index+2,index+6);
         char letter = (char) Integer.parseInt(charStr, 16 );
          buffer.append(letter);
                index+=6;
         }
         return buffer.toString();
  }
public static void main(String[] args) {
// TODO Auto-generated method stub
Test t = new Test();
String s = "中文";
String rs = t.chineseToUnicode(s);
System.out.println("unicode: "+rs.trim());
System.out.println("chinese: "+t.UnicodeTochinese(rs.trim()));
}

抱歉!评论已关闭.