Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you convert a String to a Java string literal?

Tags:

java

string

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.

like image 273
Simon Nickerson Avatar asked Mar 16 '10 09:03

Simon Nickerson


People also ask

What is string and string literal in Java?

A string literal in Java is basically a sequence of characters from the source character set used by Java programmers to populate string objects or to display text to a user. These characters could be anything like letters, numbers or symbols which are enclosed within two quotation marks.

Can we change string literals Java?

In Java, keep in mind that String objects are immutable, which means the object cannot be changed once it's created. StringBuffer and StringBuilder objects, on the other hand, are mutable, meaning they can be changed after they're created.

What does string literal mean in Java?

A string literal is simply a reference to an instance of the String class, which consists of zero or more characters enclosed in double quotes. Moreover, a string literal is also a constant, which means it always refers to the same instance of the String class, due to interning [2].


2 Answers

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

like image 58
unwind Avatar answered Oct 09 '22 08:10

unwind


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();
}
like image 20
Simon Nickerson Avatar answered Oct 09 '22 09:10

Simon Nickerson