Java String Unicode Value

前端 未结 2 947
没有蜡笔的小新
没有蜡笔的小新 2020-12-15 08:31

How can I get the unicode value of a string in java?

For example if the string is \"Hi\" I need something like \\uXXXX\\uXXXX

2条回答
  •  无人及你
    2020-12-15 08:46

    This method converts an arbitrary String to an ASCII-safe representation to be used in Java source code (or properties files, for example):

    public String escapeUnicode(String input) {
      StringBuilder b = new StringBuilder(input.length());
      Formatter f = new Formatter(b);
      for (char c : input.toCharArray()) {
        if (c < 128) {
          b.append(c);
        } else {
          f.format("\\u%04x", (int) c);
        }
      }
      return b.toString();
    }
    

提交回复
热议问题