turbo
turbo

Reputation: 589

How to change string encoding

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());

Upvotes: 1

Views: 82

Answers (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());

Upvotes: 1

Related Questions