Java 如何从十六进制编码字符串解码为UTF-8字符串
我得到HTML Javascript字符串,如:Java 如何从十六进制编码字符串解码为UTF-8字符串,java,javascript,Java,Javascript,我得到HTML Javascript字符串,如: htmlString = "https\x3a\x2f\x2ftest.com" 但我想解码如下: str = "https://test.com" 这意味着,我需要一个Util API,如: public static String decodeHex(String htmlString){ // do decode and converter here } public static void main(String ..
htmlString = "https\x3a\x2f\x2ftest.com"
但我想解码如下:
str = "https://test.com"
这意味着,我需要一个Util API,如:
public static String decodeHex(String htmlString){
// do decode and converter here
}
public static void main(String ...args){
String htmlString = "https\x3a\x2f\x2ftest.com";
String str = decodeHex(htmlString);
// str should be "https://test.com"
}
有人知道如何实现这个API-DECODEX吗 这应该足够让你开始了。我把实现hexDecode和整理格式错误的输入作为练习留给您
public String decode(String encoded) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < encoded.length(); i++) {
if (encoded.charAt(i) == '\' && (i + 3) < encoded.length() && encoded.charAt(i + 1) == 'x') {
sb.append(hexDecode(encoded.substring(i + 2, i + 4)));
i += 3;
} else {
sb.append(encoded.charAt(i));
}
}
return sb.toString;
}
公共字符串解码(字符串编码){
StringBuilder sb=新的StringBuilder();
for(int i=0;i
公共字符串解码(字符串编码)抛出解码异常{
StringBuilder sb=新的StringBuilder();
for(int i=0;i
很好,但我想要一个Java API来实现相同的功能。
public String decode(String encoded) throws DecoderException {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < encoded.length(); i++) {
if (encoded.charAt(i) == '\\' && (i + 3) < encoded.length() && encoded.charAt(i + 1) == 'x') {
sb.append(new String(Hex.decodeHex(encoded.substring(i + 2, i + 4).toCharArray()),StandardCharsets.UTF_8));
i += 3;
} else {
sb.append(encoded.charAt(i));
}
}
return sb.toString();
}