网上大多都只支持纯中文字符串转换,我修改了一下,支持中英文字符串的转换,代码如下:
/**
* @author lifm
*
*/
public class StringUtil {
public static String gbk2Unicode(String str) {
StringBuffer ret = new StringBuffer();
String tmp = null;
try {
byte[] bb = str.getBytes("UTF-16");
for (int i = 3; i < bb.length; i+=2) {
//i++;
if (bb[i - 1] != 0)
tmp = toHEXString(bb[i - 1]) + toHEXString(bb[i]);
else
tmp = "00" + toHEXString(bb[i]);
ret.append("//u").append(tmp);
}
return ret.toString();
} catch (Exception e) {
// TODO: handle exception
return str;
}
}
public static String unicode2GBK(String str) {
String[] s = str.split("u");
StringBuffer ret = new StringBuffer();
for(int i = 1 ; i < s.length; i++ ) {
ret.append((char)Integer.parseInt(s[i], 16));
}
return ret.toString();
}
private static String toHEXString(byte b) {
return ("" + "0123456789ABCDEF".charAt(0xf & b >> 4) + "0123456789ABCDEF"
.charAt(b & 0xF));
}
}