Unicode(統一碼、萬國碼、單一碼)是計算機科學領域里的一項業界標准,包括字符集、編碼方案等。Unicode 是為了解決傳統的字符編碼方案的局限而產生的,它為每種語言中的每個字符設定了統一並且唯一的二進制編碼,以滿足跨語言、跨平台進行文本轉換、處理的要求。1990年開始研發,1994年正式公布。
public class ConvertUtils { /** * 字符串轉unicode * @param str * @return */ public static String str2Unicode(String str) { str = (str == null ? "" : str); String tmp; StringBuffer sb = new StringBuffer(1000); char c; int i, j; sb.setLength(0); for (i = 0; i < str.length(); i++) { c = str.charAt(i); sb.append("\\u"); j = (c >>> 8); // 取出高8位 tmp = Integer.toHexString(j); if (tmp.length() == 1) sb.append("0"); sb.append(tmp); j = (c & 0xFF); // 取出低8位 tmp = Integer.toHexString(j); if (tmp.length() == 1) sb.append("0"); sb.append(tmp); } return sb.toString(); } /** * 字符串轉unicode * * @param str * @return */ public static String strToUnicode(String str) { StringBuilder sb = new StringBuilder(); char[] c = str.toCharArray(); for (int i = 0; i < c.length; i++) { sb.append("\\u" + Integer.toHexString(c[i])); } return sb.toString(); } /** * unicode轉字符串 * * @param unicode * @return */ public static String unicodeToStr(String unicode) { StringBuilder sb = new StringBuilder(); String[] hex = unicode.split("\\\\u"); for (int i = 1; i < hex.length; i++) { int index = Integer.parseInt(hex[i], 16); sb.append((char) index); } return sb.toString(); } public static void main(String[] args) { String ucode=str2Unicode("Hollow 世界"); System.out.println(ucode); System.out.println(unicodeToStr(ucode)+"\n"); ucode=strToUnicode("Hollow 新世界"); System.out.println(ucode); System.out.println(unicodeToStr(ucode)); } }
輸出:
\u0048\u006f\u006c\u006c\u006f\u0077\u0020\u4e16\u754c
Hollow 世界
\u48\u6f\u6c\u6c\u6f\u77\u20\u65b0\u4e16\u754c
Hollow 新世界