import java.io.IOException;
import java.io.UnsupportedEncodingException;java
public class SmartUnicode {
private static SmartUnicode uniCode=null;數組
/**
* 根據傳入的字符構造unicode 碼
* @param ch
* @return
*/
public static String decode(char ch) {
char[] chs = new char[] { ch };
String str = new String(chs);
try {
byte[] bytes = str.getBytes("unicode");
int i = bytes[3];//取unicode的高位數
if (i < 0) {
i = 256 + i;
}
String tohexStr = Integer.toHexString(i);//將字符串轉換爲16進制數
i = bytes[2];
if (i < 0) {
i = 256 + i;
}
String tohexStr2 = Integer.toHexString(i);//將字符串轉換爲16進制數
return "\\u" + tohexStr + tohexStr2;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";ide
}code
/**
* 將字符串轉換字節數組
* @param str
* @return
*/
public static String decodeStr(String str) {
char[] chars = str.toCharArray();
String result = "";
for (int i = 0; i < chars.length; i++) {
result = result + uniCode.decode(chars[i]);
}
return result;
}
/**
* 將中文轉換爲unicode碼
* @param str
* @return
*/
public static String native2ascii(String str){
int len = str.getBytes().length;
if (len == str.length() * 2) { //純中文字符集 如:中國
return uniCode.decodeStr(str);
} else { //中文與字符混合 如:中ch1國
String result = "";
for (int pos = 0; pos < str.length(); pos++) {
String substr = str.substring(pos, pos + 1);
if (substr.length()*2 == substr.getBytes().length) {
result = result + uniCode.decodeStr(substr);
} else
result = result + substr;
}
return result;
}
}
public static void main(String[] args) throws IOException {
SmartUnicode smd = new SmartUnicode();
smd.native2ascii("產品s@ds^1f世界");
}
}ci