6

I used the following code to replace occurrence of '\' but its not working.

msg="\uD83D\uDE0A";
msg=msg.replace("\\", "|");

I spent a lot of time in Google. But didn't find any solution.

Also tried

msg="\uD83D\uDE0A";
msg=msg.replace("\", "|");
Daniel Olszewski
  • 13,995
  • 6
  • 58
  • 65

3 Answers3

4

The msg string defined must also use an escape character like this:

msg="\\uD83D\\uDE0A";
msg=msg.replace("\\", "|");

That code will work and it will result in: |uD83D|uDE0A

reidzeibel
  • 1,622
  • 1
  • 19
  • 24
0

If you want to show the unicode integer value of a unicode character, you can do something like this:

String.format("\\u%04X", ch);

(or use "|" instead of "\\" if you prefer).

You could go through each character in the string and convert it to a literal string like "|u####" if that is what you want.

khelwood
  • 55,782
  • 14
  • 81
  • 108
0

From what I understand, you want to get the unicode representation of a string. For that you can use the answer from here.

private static String escapeNonAscii(String str) {

  StringBuilder retStr = new StringBuilder();
  for(int i=0; i<str.length(); i++) {
    int cp = Character.codePointAt(str, i);
    int charCount = Character.charCount(cp);
    if (charCount > 1) {
      i += charCount - 1; // 2.
      if (i >= str.length()) {
        throw new IllegalArgumentException("truncated unexpectedly");
      }
    }

    if (cp < 128) {
      retStr.appendCodePoint(cp);
    } else {
      retStr.append(String.format("\\u%x", cp));
    }
  }
  return retStr.toString();
}

This will give you the unicode value as a String which you can then replace as you like.

Community
  • 1
  • 1
Codebender
  • 14,221
  • 7
  • 48
  • 85