`

Unicode字符串 显示成汉字

阅读更多

   前段时间,人人站内信改版,本来能正常显示的发信人名字,现在返回一个json串,需要解析json串以正常显示。发信人的名字以unicode编码方式存在json串中,要想正常显示发信人的名字,需要进行unicode到汉字的转换操作。

    本身java 是支持unicode 编码的,所以像 str = "\u4e2d\u56fd"; 打印出来是正常的。这里要是对 str = "\\u4e2d\\u56fd"; 这种形式的unicode码进行的转换。

 

    汉字转 unicode 可以用 Integer.toHexString(ch)。

    unicode 转汉字关键的是 (char)Integer.parseInt("4e2d", 16)。

  

	public static void testUDecode() {
		
		//将汉字转换为十六进制Unicode表示
		for (char ch : "中国".toCharArray()) {
			if (ch > 128) {
				System.out.print("\\u" + Integer.toHexString(ch));
			} else {
				System.out.print(ch);
			}
		}
		String str = "\u4e2d\u56fd\u5b66";
		System.out.println("\n"+str);//直接打印出汉字
		
		str = "\\u5b66\\u56fd\\u5b66";
		System.out.println(str);// 打印结果为\u5b66\u56fd\u5b66
		
		//将Unicode字符串转换为汉字输出
		String s[]=str.split("\\\\u");
		String t="";
		for(int j=1;j<s.length;j++){
			int ab=Integer.valueOf(s[j],16);//先将16进制转换为整数
			char ac=(char)ab;//再将整数转换为字符
			System.out.println(ac);
			t=t+ac;
		}
		System.out.println("t:"+t);

		char a=20320;
		int b=(int)a; 
		System.out.println(a+","+b);
	}

输出结果为:
\u4e2d\u56fd
中国学
\u5b66\u56fd\u5b66
学
国
学
t:学国学
你,20320

 

分享到:
评论
1 楼 飘逝天涯 2011-09-28  
帮助很大,感谢楼主!

相关推荐

Global site tag (gtag.js) - Google Analytics