views:

40

answers:

3
+2  Q: 

Encoding in Java

Hi, I have a string with special characters in Java.

"[^\\"]*\\"

I want to convert it to HTML entities like this:

"[^\\"]*\\"

How this could be achieved in Java?

A: 

You need to parse the input string character by character and look for particular ones that you want to convert. When you find a match, simply replace that character with the HTML entity.

Shakedown
A: 

Use String.replace() as needed:

"[^\\\"]*\\".replace("\"", """);
krock
I wasn't allowed to increase the library size. So, chose this method and implemented it.
Rajkumar
+1  A: 

Apache Commons Lang includes a helper for encoding HTML. StringEscapeUtils.escapeHtml() should do the trick. According to the javadocs it "Supports all known HTML 4.0 entities, including funky accents".

Asaph