如何将带有Unicode字符的字符串转换为普通字符串?

3

我哪里做错了?

我从服务器收到一个字符串,值为"%u0419%u043E"。

我试图将其转换为普通字符串,但是我看到了中文字符。这是错误的,因为传入的字母是西里尔字母。

代码:

// String test = ""%u0419%u043E"; <--- this is Йо ( cyrillic )
byte[] test = { (byte) 0x25, (byte) 0x75, (byte)0x30, (byte)0x34, (byte)0x31, (byte) 0x39,(byte) 0x25, (byte) 0x75, (byte)0x30, (byte)0x34, (byte)0x33, (byte) 0x45};
String aaa = new String(test, "UTF-16");
aaa = new String(test, "UTF-8");
aaa = new String(test, "ISO-8859-5");

这张图片展示了我的工作内容: enter image description here
1个回答

2
据我所知,这不是标准编码,至少不属于UTF-*或ISO-*之一。
您需要自行解码,例如:
public static String decode(String encoded) {
    // "%u" followed by 4 hex digits, capture the digits
    Pattern p = Pattern.compile("%u([0-9a-f]{4})", Pattern.CASE_INSENSITIVE);

    Matcher m = p.matcher(encoded);
    StringBuffer decoded = new StringBuffer(encoded.length());

    // replace every occurrences (and copy the parts between)
    while (m.find()) {
        m.appendReplacement(decoded, Character.toString((char)Integer.parseInt(m.group(1), 16)));
    }

    m.appendTail(decoded);
    return decoded.toString();
}

这个提供了:
System.out.println(decode("%u0419%u043E"));
Йо

如何替换包含 %20 的完整输入字符串?示例:"%u0419%u043E%20" - DQuade
%XX 似乎是标准的 URL 编码,因此您可以使用 java.net.URLDecoder.decode(someString, "UTF-8")。如果字符串同时包含 %uXXXX%XX,则必须先进行自定义解码(它将不会影响 URL 编码的字符)。 - bwt
是的,我使用你回答中的相同方式:在第一次解码后,我使用新的模式 %([0-f]{2}) 和新的匹配器。问题已关闭。 - DQuade

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接