11

This is sort of the Java analogue of this question about C#.

Suppose I have a String object which I want to represent in code and I want to produce a string literal that maps to the same thing.

Example

hello, "world"
goodbye

becomes

hello, \"world\"\ngoodbye

I was just about to write a state machine that ingests the string character by character and escapes appropriately, but then I wondered if there was a better way, or a library that provides a function to do this.

Community
  • 1
  • 1
Simon Nickerson
  • 42,159
  • 20
  • 102
  • 127

2 Answers2

9

If you can add external code, Apache's Commons Text has StringEscapeUtils.escapeJava() which I think does exactly what you want.

Peter Lamberg
  • 8,151
  • 3
  • 55
  • 69
unwind
  • 391,730
  • 64
  • 469
  • 606
  • 2
    EscapeStringUtils.escapeJava() doesn't do outer quotes, if the string is non-null. I would need to wrap it with: (s == null)? null : "\""+StringEscapeUtils.escapeJava(s)+"\""; – Max Spring Dec 23 '12 at 00:38
4

My naive state machine implementation looks like this:

public String javaStringLiteral(String str)
{
    StringBuilder sb = new StringBuilder("\"");
    for (int i=0; i<str.length(); i++)
    {
        char c = str.charAt(i);
        if (c == '\n')
        {
            sb.append("\\n");
        }
        else if (c == '\r')
        {
            sb.append("\\r");
        }
        else if (c == '"')
        {
            sb.append("\\\"");
        }
        else if (c == '\\')
        {
            sb.append("\\\\");
        }
        else if (c < 0x20)
        {
            sb.append(String.format("\\%03o", (int)c));
        }
        else if (c >= 0x80)
        {
            sb.append(String.format("\\u%04x", (int)c));
        }
        else
        {               
            sb.append(c);
        }
    }
    sb.append("\"");
    return sb.toString();
}
Simon Nickerson
  • 42,159
  • 20
  • 102
  • 127