首页 > 解决方案 > utf-8 to string 获得额外添加的字符

问题描述

在安卓

当我从服务器获取 utf-8 结果并将服务器的输出转换为字符串时,我会在字符串中添加额外的转义字符。

在代码中会发生什么

String unicodeMessage =  "\u09aa\u09cd\u09b0\u099c\"; //this is how I want it

String unicodeMessage = "\\u09aa\\u09cd\\u09b0\\u099c\\"; // this is what happens

我试过做之前帖子中提到的字节方法,但它不起作用

byte[] bytes = unicodeMessage.getBytes("UTF-8");
answer = new String(bytes, "UTF-8");

我得到与输入字符串相同的输出。

有没有办法可以删除添加的转义字符?

 String bengali = "\\u09aa\\u09cd\\u09b0\\u099c\\u099c"; //this is the input 

//\u09aa\u09cd\u09b0\u099c\u099c is the output i get when i print bengali and use replace("\\\\","\\"); 

 //প্রজজ is the expected output when input = "\u09aa\u09cd\u09b0\u099c\u099c"

 // u09aau09cdu09b0u099cu099c output when i use replace("\\","")

标签: androidarraysstringutf-8textview

解决方案


您在单个 unicode 字符串中所拥有\u09aa的是字符的十六进制值(09aa=2474十进制)用\u. 因此,您需要解析这些值并将它们转换为真正的 unicode 字符。以下是执行此操作的函数:

public static String getRealUnicodeString(String unicodeInput) {
    Pattern pattern = Pattern.compile("\\\\u([0-9a-fA-F]+)");
    Matcher m = pattern.matcher(unicodeInput);
    while (m.find()) {
        String unicodeChar = m.group(1);
        unicodeInput = unicodeInput.replaceAll("\\\\u" + unicodeChar, String.valueOf((char) Integer.parseInt(unicodeChar, 16)));
    }
    return unicodeInput;
}

然后使用它:

System.out.println(getRealUnicodeString("\\u09aa\\u09cd\\u09b0\\u099c\\u099c \n StackoveFlow"));

推荐阅读