package text; public class Convert { public static String toString( char value ) { switch ( value ) { case '\b': return "\\b"; case '\f': return "\\f"; case '\n': return "\\n"; case '\r': return "\\r"; case '\t': return "\\t"; case '\\': case '\"': case '\'': return "\\" + value; default: if ( value < 32 || value >= 127 ) return "\\" + toOctalString( value ); else return "" + value; } } public static String toString( String s ) { String result = ""; for ( int i = 0; i < s.length(); i++ ) result += toString( s.charAt( i ) ); return result; } public static String toOctalString( char value ) { String result = ""; result += value / 64; value %= 64; result += value / 8; value %= 8; result += value; return result; } public static String parseString( String input ) { String output = ""; int i = 0; char inputChar; char outputChar; while ( i < input.length() ) { inputChar = input.charAt( i ); if ( inputChar == '\\' ) { i++; if ( i >= input.length() ) throw new Error( "Invalid Text String" ); inputChar = input.charAt( i ); switch ( inputChar ) { case 'b': output += '\b'; i++; break; case 'f': output += '\f'; i++; break; case 'n': output += '\n'; i++; break; case 'r': output += '\r'; i++; break; case 't': output += '\t'; i++; break; case 'x': case 'X': case 'u': { outputChar = 0; i++; for ( int j = 0; i < input.length() && j < 2; j ++ ) { inputChar = input.charAt( i ); if ( inputChar >= '0' && inputChar <= '9' ) { outputChar = ( char ) ( outputChar * 0x10 + inputChar - '0' ); i++; } else if ( inputChar >= 'a' && inputChar <= 'f' ) { outputChar = ( char ) ( outputChar * 0x10 + inputChar - 'a' + 0xa ); i++; } else if ( inputChar >= 'A' && inputChar <= 'F' ) { outputChar = ( char ) ( outputChar * 0x10 + inputChar - 'A' + 0xa ); i++; } else break; } output += outputChar; } // end while loop break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { outputChar = 0; for ( int j = 0; i < input.length() && j < 3; j ++ ) { inputChar = input.charAt( i ); if ( inputChar >= '0' && inputChar <= '7' ) { outputChar = ( char ) ( outputChar * 010 + inputChar - '0' ); i++; } else break; } // end while loop output += outputChar; } break; default: output += inputChar; i++; } // end cases } // end then else if ( inputChar == '%' ) { output += "%%"; i++; } else { output += inputChar; i++; } } // end while loop return output; } public static Character parseChar( String input ) { String output = parseString( input ); if ( output.length() == 1 ) return new Character( output.charAt( 0 ) ); else throw new Error( "Invalid Text String" ); } }