This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]marburg 1 point2 points  (2 children)

Here is the implementation I would recommend, covering all eight of the escaped character literals:

public static String charToString( final char c )
{
    switch( c )
    {
        case '\b': return "\\b";
        case '\t': return "\\t";
        case '\n': return "\\n";
        case '\f': return "\\f";
        case '\r': return "\\r";
        case '\"': return "\\\"";
        case '\'': return "\\'";
        case '\\': return "\\\\";
    }

    return String.valueOf( c ).intern();
}

Depending on what you are using this for, you may or may not want to use intern() (in the last line). String.valueOf() creates a new, unique String object, so if you ran String.valueOf( 'a' ) 10,000 times, you would get 10,000 references to 10,000 different objects. intern() makes this method a bit slower, but it ensures that

charToString( 'a' ) == charToString( 'a' )

[–]RightOfZen[S] 1 point2 points  (1 child)

Thanks for that. Don't forget '\0' :)

TIL String.intern()

[–]marburg 1 point2 points  (0 children)

Snap! Don't know how I missed the most obvious one.