utf-8 到字符串获取额外添加的字符
utf-8 to string gets extra added characters
在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("\","")
像 \u09aa
这样的单个 unicode 字符串中的内容是用 \u
转义的字符的十六进制值(09aa
= 2474
十进制)。因此,您需要解析这些值并将它们转换为真正的 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 结果并将服务器的输出转换为字符串时,发生的事情是我在字符串中添加了额外的转义字符。
在代码中发生的是
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 字符串中的内容是用 \u
转义的字符的十六进制值(09aa
= 2474
十进制)。因此,您需要解析这些值并将它们转换为真正的 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"));