/* * [ToJavaStringLiteral.java] * * Summary: convert java reserved chars in strings by quoting them with \. * * Copyright: (c) 2002-2017 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.8+ * * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/ * * Version History: * 1.0 2002-06-19 */ package com.mindprod.quoter; import com.mindprod.common18.ST; /** * convert java reserved chars in strings by quoting them with \. * * @author Roedy Green, Canadian Mind Products * @version 1.0 2002-06-19 * @since 2002-06-19 */ public final class ToJavaStringLiteral extends Translator { private static final String[] trt; static { // initialize the table array trt = new String[ 256 ]; for ( int i = 0; i < 32; i++ ) { // to octal \077 trt[ i ] = "\\" + ST.toLZOctalString( i, 3 ); } for ( int i = 32; i < 127; i++ ) { // leave char unmolested. trt[ i ] = String.valueOf( ( char ) i ).intern(); } for ( int i = 127; i < 161; i++ ) { // control chars, should not really be in Java source. trt[ i ] = "\\u" + ST.toLZHexString( i, 4 ); } for ( int i = 161; i < 256; i++ ) { // to hex \ u h h h h trt[ i ] = "\\u" + ST.toLZHexString( i, 4 ); } // overrides trt[ 8 ] = "\\b";/* Backspace character */ trt[ 9 ] = "\\t";/* TAB */ trt[ 10 ] = "\\n\"\n + \""; /* starts a new line with + */ trt[ 12 ] = "\\f";/* Form Feed */ trt[ 13 ] = "\\r";/* cr */ trt[ '\"' ] = "\\\""; /* \" */ // trt[ '\'' ] = "\\\'"; /* \' */ trt[ '\\' ] = "\\\\"; /* \\ */ } // end static init // instance init. { table = trt; } /** * convert string, extender can override this default implementation. * * @param raw String to be converted * * @return converted string. By default use table[] to translate char by char for 0..255 and leaves higher chars as * is. */ public String process( String raw ) { assert raw != null : "Translator.process raw must not be null"; assert table != null : "table must be set by Translator implementor"; StringBuilder cooked = new StringBuilder( raw.length() * 120 / 100 ); // enclose whole string in quotes cooked.append( " \"" ); for ( int i = 0; i < raw.length(); i++ ) { char c = raw.charAt( i ); if ( c < 256 ) { cooked.append( table[ c ] ); } else { cooked.append( "\\u" ); cooked.append( ST.toLZHexString( c, 4 ) ); } } // end for // get rid of trailing junk, we may have appended too much. int length = cooked.length(); if ( length >= 5 && cooked.substring( length - 5 ).equals( "\n + \"" ) ) { // remove junk off the end. cooked.setLength( length - 5 ); } cooked.append( "\"" ); return cooked.toString(); } // end process }