Jarish Jose
Jarish Jose

Reputation: 91

String replace function not working in android

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("\", "|");

Upvotes: 6

Views: 363

Answers (3)

Codebender
Codebender

Reputation: 14471

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.

Upvotes: 0

khelwood
khelwood

Reputation: 59096

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.

Upvotes: 0

reidzeibel
reidzeibel

Reputation: 1632

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

Upvotes: 4

Related Questions