1

I have a string as "hello❤️ #xyz". There is emoji between hello and #xyz. I need final string with UTF-8 decoded string as

"hello \ud83c\udf1c #xyz".

How do i achieve this. I was able to convert whole string as

\u0068\u0065\u006C\u006C\u006F\u2764\uFE0F\u0020\u0023\u0078\u0079\u007A

with this code

String s = "hello❤️ #xyz";
StringBuffer sb = new StringBuffer();
for (char ch : s.toCharArray()) {
        sb.append(String.format("\\u%04X", (int)ch));       
}
System.out.printf(sb.toString());

1 Answer 1

1

Like this?

String s = "hello❤️ #xyz";
StringBuffer sb = new StringBuffer();
for (char ch : s.toCharArray()) {
    if(ch >= 32 && ch <= 126)
        sb.append(ch); // ch is a printable ASCII character
    else
        sb.append(String.format("\\u%04X", (int)ch));       
}
System.out.printf(sb.toString());
Sign up to request clarification or add additional context in comments.

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.