android - utf-8 到字符串获取额外添加的字符

标签 android arrays string utf-8 textview

在安卓中

当我从服务器获取 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("\\","")

最佳答案

\u09aa 这样的单个 unicode 字符串是字符的十六进制值(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"));

关于android - utf-8 到字符串获取额外添加的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52660789/

相关文章:

C# 用两个冒号分割单词

c++ - 书中的代码未运行 - 旧语法或错误代码?

单击 url 时的 Android 打开 Activity

Android 工具栏覆盖了一个 fragment

arrays - Bash 在 while 循环中构建数组(不持久)?

python - 通过 URL 发送列表

java - Android 10 及更高版本上的即时应用内更新会在安装/重启后关闭应用

android - 构造函数通知已弃用

java - Swig:将无符号字符数组从 C++ 传递到 Java

python - 数组太大,无法在 matlab 中除法,但不能在 python 中除法