【问题标题】:How to convert string with Unicode characters to normal String?如何将带有 Unicode 字符的字符串转换为普通字符串?
【发布时间】:2016-06-18 00:11:27
【问题描述】:

我哪里失败了?

我有来自服务器的传入字符串,值为“%u0419%u043E”。

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

代码:

// 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");

图片解释了我的工作:

【问题讨论】:

    标签: android string unicode


    【解决方案1】:

    据我所知,这不是标准编码,至少不是 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”
    • %XX 好像是标准的 URL 编码,所以可以使用java.net.URLDecoder.decode(someString, "UTF-8")。如果字符串同时包含%uXXXX%XX,则必须先进行自定义解码(它将保持 URL 编码字符不变)
    • 是的,我在您的回答中使用与上述相同的方式:第一次解码后,我使用新模式 %([0-f]{2}) 和新匹配器。问题已结束
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 2021-09-21
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多