public static String escape ( String text ) { boolean hasQuote = text . indexOf ( QUOTE ) >= 0 ; boolean hasComma = text . indexOf ( COMMA ) >= 0 ; if ( ! ( hasQuote || hasComma ) ) { return text ; } StringBuilder builder = new StringBuilder ( ) ; if ( hasQuote ) { for ( int i = 0 ; i < text . length ( ) ; i ++ ) { char c = text . charAt ( i ) ; if ( c == QUOTE ) { builder . append ( QUOTE_ESCAPED ) ; } else { builder . append ( c ) ; } } } else { builder . append ( text ) ; } if ( hasComma ) { builder . insert ( 0 , QUOTE ) ; builder . append ( QUOTE ) ; } return builder . toString ( ) ; }
Escape input for CSV