static protected String escapeString ( String s ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int c = s . charAt ( i ) ; switch ( c ) { case ' ' : buf . append ( "\\\"" ) ; break ; case ' ' : buf . append ( "\\\\" ) ; break ; case ' ' : buf . append ( ' ' ) ; break ; case ' ' : buf . append ( ' ' ) ; break ; case ' ' : buf . append ( ' ' ) ; break ; case ' ' : buf . append ( ' ' ) ; break ; default : if ( c < ' ' ) buf . append ( String . format ( "\\x%02x" , ( c & 0xff ) ) ) ; else buf . append ( ( char ) c ) ; break ; } } return buf . toString ( ) ; }
Given a typical string insert backslashes before and \\ characters and control characters .