0

I want to convert following string to an escaped String.

I am using StringEscapeUtils.escapeJava(), but it didn't escape the brackets.

For example:

val str = "(안녕하세요.)";
System.out.println(StringEscapeUtils.escapeJava(str))

Expected:

\\u0028\\uC548\\uB155\\uD558\\uC138\\uC694\\u002e\\u0029

Actual:

(\\uC548\\uB155\\uD558\\uC138\\uC694.)

I want to know the reason why it cannot convert to expected and how to convert to expected.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
thlee
  • 1

2 Answers2

2

Here's a minimal 1-liner that converts all chars to their escaped form:

str = str.chars().mapToObj(c -> String.format("\\u%04x", c)).collect(joining());

See live demo.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

Means:

  • your expectation is rather "exotic"
  • behavior could have changed with StringEscapeUtils version/namespace/package (??)

But no problem

(deleting the if-block + obsolete code (i.e. extra effort) from top answer)

@Test
void testEncoding() {
 final String src = "(안녕하세요.)"; // this has to be read with the right encoding (!)
 final StringBuilder result = new StringBuilder();
 src.chars().forEach(ch -> {
   result
     .append("\\u")
     .append(
       Integer.toHexString(0x10000 | ch)
       .substring(1)
       .toUpperCase() // or lower case, if you like ;)
     );
 });
 System.out.println(result);
}

(+ java updates)

We get:

\u0028\uC548\uB155\uD558\uC138\uC694\u002E\u0029
xerx593
  • 12,237
  • 5
  • 33
  • 64