简体   繁体   中英

How to get the real characters from its raw utf format in Java

I have some chinese charactors encoded like this:

String b = "\\u91d1\\u5143\\u6bd4\\u8054\\u6210\\u957f\\u52a8\\u529b";

How can I change the string b into the real characters, I found the below c can be shown when I output it in the console, then the question would be how to change the string b into c?

String c = "\u91d1\u5143\u6bd4\u8054\u6210\u957f\u52a8\u529b";

If the String actually contains double-slashes in it, then you will have to scan through the string manually, decoding and replacing each "\\uXXXX" sequence with its actual UTF-16 representation. For example (untested):

StringBuilder buf = new StringBuilder();
char c[2];
for (int i = 0; i < b.length(); i += 7)
{
  int tmp = Integer.parseInt(b.substring(i+3, i+7), 16);
  if (tmp < 0x1000)
  {
    c[0] = (char) tmp;
    c[1] = 0;
  }
  else
  {
    tmp -= 0x10000;
    c[0] = (0xD800 | ((tmp & 0xFFC00) >> 10));
    c[1] = (0xDC00 | (tmp & 0x3FF));
  }
  buf.append(c, 2);
}
b = buf.ToString();

Someone posted a tricky solution but seems good for me:

    b="abc="+b;
    Properties props = new Properties();
    props.load(new StringReader(b));
    b=props.getProperty("abc");
    System.out.println(b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM