public class UnicodeDecoderUtil {
public static String escape(String str) {
int i;
char j;
StringBuffer tmp = new StringBuffer();
tmp.ensureCapacity(str.length() * 6);
for (i = 0; i < str.length(); i++) {
j = str.charAt(i);
if (Character.isDigit(j) || Character.isLowerCase(j) || Character.isUpperCase(j)) {
tmp.append(j);
} else {
tmp.append("&#x");
tmp.append(Integer.toString(j, 16));
tmp.append(";");
}
}
return tmp.toString();
}
public static String unescape(String hexStr) {
StringBuffer tmp = new StringBuffer();
String prefStr = "&#x";
String laterStr = ";";
tmp.ensureCapacity(hexStr.length());
int lastPos = 0, pref = 0, later = 0;
char ch;
while (lastPos < hexStr.length()) {
pref = hexStr.indexOf(prefStr, lastPos);
later = hexStr.indexOf(laterStr, pref);
if (pref == lastPos) {
ch = (char) Integer.parseInt(hexStr.substring(pref + 3, later), 16);
tmp.append(ch);
lastPos = later + 1;
} else {
if (pref == -1) {
tmp.append(hexStr.substring(lastPos));
lastPos = hexStr.length();
} else {
tmp.append(hexStr.substring(lastPos, pref));
lastPos = pref;
}
}
}
return tmp.toString();
}
public static String unescapeHexToDec(String hexStr) {
StringBuffer tmp = new StringBuffer();
String prefStr = "&#x";
String laterStr = ";";
tmp.ensureCapacity(hexStr.length());
int lastPos = 0, pref = 0, later = 0;
while (lastPos < hexStr.length()) {
pref = hexStr.indexOf(prefStr, lastPos);
later = hexStr.indexOf(laterStr, pref);
if (pref == lastPos) {
tmp.append(prefStr);
tmp.append(Integer.parseInt(hexStr.substring(pref + 3, later), 16));
tmp.append(laterStr);
lastPos = later + 1;
} else {
if (pref == -1) {
tmp.append(hexStr.substring(lastPos));
lastPos = hexStr.length();
} else {
tmp.append(hexStr.substring(lastPos, pref));
lastPos = pref;
}
}
}
return tmp.toString();
}
public static String unescapeDecToHex(String decStr) {
StringBuffer tmp = new StringBuffer();
String prefStr = "&#x";
String laterStr = ";";
tmp.ensureCapacity(decStr.length());
int lastPos = 0, pref = 0, later = 0;
while (lastPos < decStr.length()) {
pref = decStr.indexOf(prefStr, lastPos);
later = decStr.indexOf(laterStr, pref);
if (pref == lastPos) {
tmp.append(prefStr);
tmp.append(Integer.toHexString(Integer.parseInt(decStr.substring(pref + 3, later))));
tmp.append(laterStr);
lastPos = later + 1;
} else {
if (pref == -1) {
tmp.append(decStr.substring(lastPos));
lastPos = decStr.length();
} else {
tmp.append(decStr.substring(lastPos, pref));
lastPos = pref;
}
}
}
return tmp.toString();
}
public static void main(String[] args) {
String str = "測試字串";
String str2 = "测试隔開字符串內容";
System.out.println("編碼:" + escape(str));
System.out.println("解碼:" + unescape(str2));
String str3 = unescapeHexToDec(str2);
System.out.println("轉成10進位制編碼:" + str3);
String str4 = unescapeDecToHex(str3);
System.out.println("轉成16進位制編碼:" + str4);
}
}