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

后端 未结 2 1555
梦如初夏
梦如初夏 2021-01-11 18:26

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 st

相关标签:
2条回答
  • 2021-01-11 19:05

    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();
    }
    
    0 讨论(0)
  • 2021-01-11 19:15

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

    0 讨论(0)
提交回复
热议问题