android - 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("\\","")
解决方案
您在单个 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"));
推荐阅读
- latex - 如何有效地阻止具有字体颜色的文本?
- vba - 原项目太大时如何制作ACCDE文件
- rest - 使用 rest Api 将 solines 添加到 acumatica
- r - 如何在 gganimate 上添加交点?
- python-trio - 如何使用 trio 构建开始和结束同步调用?
- docker - 如何保存 docker 容器?
- list - 如何将项目添加到 Ansible 中的现有字典?
- javascript - 创建一个接受数字数组的函数
- javascript - 从 Bokeh Google Maps 包装器 (fitBounds()) 调用 Javascript 方法
- ios - 如何在 View Swift 顶部添加标签