public static String escape ( CharSequence string ) { StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < string . length ( ) ; ++ i ) { char c = string . charAt ( i ) ; switch ( c ) { case ' ' : builder . append ( ' ' ) . append ( ' ' ) ; break ; case ' ' : builder . append ( ' ' ) . append ( ' ' ) ; break ; case ' ' : builder . append ( ' ' ) . append ( ' ' ) ; break ; case ' ' : builder . append ( ' ' ) . append ( ' ' ) ; break ; case ' ' : builder . append ( ' ' ) . append ( ' ' ) ; break ; case ' ' : case ' ' : builder . append ( ' ' ) . append ( c ) ; break ; case ' ' : builder . append ( ' ' ) . append ( ' ' ) ; break ; default : if ( c < 32 || c == 127 ) { builder . append ( String . format ( "\\%03o" , ( int ) c ) ) ; } else if ( ! isConsolePrintable ( c ) || Character . isHighSurrogate ( c ) || Character . isLowSurrogate ( c ) ) { builder . append ( String . format ( "\\u%04x" , ( int ) c ) ) ; } else { builder . append ( c ) ; } break ; } } return builder . toString ( ) ; }
Properly java - escape the string for printing to console .