Convert International String to \u Codes in java

后端 未结 12 2053
离开以前
离开以前 2020-11-29 02:53

How can I convert an international (e.g. Russian) String to \\u numbers (unicode numbers)
e.g. \\u041e\\u041a for OK ?

12条回答
  •  旧时难觅i
    2020-11-29 03:16

    Here's an improved version of ArtB's answer:

        StringBuilder b = new StringBuilder();
    
        for (char c : input.toCharArray()) {
            if (c >= 128)
                b.append("\\u").append(String.format("%04X", (int) c));
            else
                b.append(c);
        }
    
        return b.toString();
    

    This version escapes all non-ASCII chars and works correctly for low Unicode code points like Ä.

提交回复
热议问题