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("\", "|");
9
  • 5
    msg="\uD83D\uDE0A"; doesn't actually contain any backslashes. The \u#### gets compiled into a unicode character Commented Jun 8, 2015 at 10:28
  • ya its a unicode of a laughing smiley. But is there any options to do as mentioned in the question? Commented Jun 8, 2015 at 10:29
  • What are you trying to do actually -- replace the smileys with a pipe character, or something else? Commented Jun 8, 2015 at 10:33
  • @MickMnemonic i want to send the unicode of smiley to my web url, but when it reaches there it missing the \. Thats why am trying to change it with |. Commented Jun 8, 2015 at 10:37
  • if you can't control the input you have to get back original string before replace .stackoverflow.com/questions/13700333/… Commented Jun 8, 2015 at 10:37

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

i cant controll the input.
what if we want to do with same input mentioned in question ?
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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.