utf-8到字符串会获得额外添加的字符

时间:2018-10-05 07:49:27

标签: android arrays string utf-8 textview

在ANDROID

当我从服务器获取utf-8结果并将服务器的输出输出到字符串时,会发生什么情况,就是我在字符串中添加了额外的转义字符。

在代码中发生的是

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

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

我尝试做以前的文章中提到的bytes方法,但是它不起作用

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("\\","")

1 个答案:

答案 0 :(得分:3)

在一个单一的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"));