Unicode字符串 顯示成漢字

轉自:http://zzqrj.iteye.com/blog/805832

  前段時間,人人站內信改版,本來能正常顯示的發信人名字,現在返回一個json串,需要解析json串以正常顯示。發信人的名字以unicode編碼方式存在json串中,要想正常顯示發信人的名字,需要進行unicode到漢字的轉換操作。

    本身java 是支持unicode 編碼的,所以像 str = "\u4e2d\u56fd"; 打印出來是正常的。這裏要是對 str = "\\u4e2d\\u56fd"; 這種形式的unicode碼進行的轉換。

 

    漢字轉 unicode 可以用 Integer.toHexString(ch)。

    unicode 轉漢字關鍵的是 (char)Integer.parseInt("4e2d", 16)。

  

Java代碼  收藏代碼
  1.     public static void testUDecode() {  
  2.           
  3.         //將漢字轉換爲十六進制Unicode表示  
  4.         for (char ch : "中國".toCharArray()) {  
  5.             if (ch > 128) {  
  6.                 System.out.print("\\u" + Integer.toHexString(ch));  
  7.             } else {  
  8.                 System.out.print(ch);  
  9.             }  
  10.         }  
  11.         String str = "\u4e2d\u56fd\u5b66";  
  12.         System.out.println("\n"+str);//直接打印出漢字  
  13.           
  14.         str = "\\u5b66\\u56fd\\u5b66";  
  15.         System.out.println(str);// 打印結果爲\u5b66\u56fd\u5b66  
  16.           
  17.         //將Unicode字符串轉換爲漢字輸出  
  18.         String s[]=str.split("\\\\u");  
  19.         String t="";  
  20.         for(int j=1;j<s.length;j++){  
  21.             int ab=Integer.valueOf(s[j],16);//先將16進制轉換爲整數  
  22.             char ac=(char)ab;//再將整數轉換爲字符  
  23.             System.out.println(ac);  
  24.             t=t+ac;  
  25.         }  
  26.         System.out.println("t:"+t);  
  27.   
  28.         char a=20320;  
  29.         int b=(int)a;   
  30.         System.out.println(a+","+b);  
  31.     }  
  32.   
  33. 輸出結果爲:  
  34. \u4e2d\u56fd  
  35. 中國學  
  36. \u5b66\u56fd\u5b66  
  37. 學  
  38. 國  
  39. 學  
  40. t:學國學  
  41. 你,20320  

 


發佈了40 篇原創文章 · 獲贊 13 · 訪問量 49萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章