字串和unicode互相轉換
阿新 • • 發佈:2019-01-01
字串轉換unicode和unicode 轉字串兩個方法希望可以幫到你。
/**
* 字串轉換unicode
*/
public static String StringToUnicode(String string) {
StringBuffer unicode = new StringBuffer();
for (int i = 0; i < string.length(); i++) {
// 取出每一個字元
char c = string.charAt(i);
// 轉換為unicode
unicode.append("\\u" + Integer.toHexString(c));
}
return unicode.toString();
}
/**
* unicode 轉字串
*/
public static String UnicodeToString(String unicode) {
StringBuffer string = new StringBuffer();
String[] hex = unicode.split("\\\\u" );
for (int i = 1; i < hex.length; i++) {
// 轉換出每一個程式碼點
int data = Integer.parseInt(hex[i], 16);
// 追加成string
string.append((char) data);
}
return string.toString();
}
}