At 12:28 PM 3/9/00 -0700, David Hay wrote:
>How about this:
>
>public class EscapeString
>{
> public static String escape( String str )
> {
> StringBuffer buf = new StringBuffer( str.length() );
> for ( int idx = 0; idx < str.length(); idx++ )
> {
> char ch = str.charAt( idx );
> switch ( ch )
> {
> case '"': buf.append( "\\\"" ); break;
> case '\\': buf.append( "\\\\" ); break;
> default: buf.append( ch ); break;
> }
> }
>
> return buf.toString();
> }
>
> public static void main( String[] args )
> {
> // Test 1
> if ( !EscapeString.escape( "No quotes" ).equals( "No quotes" ) ) {
> System.out.println( "Failed test 1" );
> }
>
> // Test 2
> if ( !EscapeString.escape( "\"quotes only\"" ).equals( "\\\"quotes
>only\\\"" ) ) {
> System.out.println( "Failed test 2" );
> }
>
> // Test 3
> if ( !EscapeString.escape( "Quotes \"stuff\" and contains backslash
>\\" ).equals( "Quotes \\\"stuff\\\" and contains backslash \\\\" ) ) {
> System.out.println( "Failed test 3" );
> }
> }
>}
>
Looks good to me, David. Thanks! I'll drop this into JDEbug (with
appropriate credit to you).
Regards,
Paul
>-----Original Message-----
>From: Paul Kinnucan [mailto:[EMAIL PROTECTED]]
>Sent: Thursday, March 09, 2000 12:17 PM
>To: [EMAIL PROTECTED]
>Subject: Wanted: Efficient String Escape Method
>
>
>Hi,
>
>I'm looking for an effient method (literally a Java method) to escape
>quotes and backslashes in a string. I need this to fix a bug in JDEbug. The
>method should do the following:
>
>1) Search for all occurences of \ in a string and replace them with \\.
>
>2) Search for all occurences of " in a string and replace them with \".
>
>Note that step 1 needs to be done first to avoid escaping the escapes for
>the quotation marks.
>
>JDEBug currently has a method that uses a simple-minded approach that
>builds the output string by concatenating it with each character of the
>input string or \" in the case of quote marks in the input string.
>
>If any of you have a spare moment and would like to take a stab at doing
>this more efficiently (e.g., with fewer object creations), I'd greatly
>appreciate it.
>
>- Paul
>
>
>
>------------------------------------------------------------
>JDE mailing list archive:
>http://www.mail-archive.com/[email protected]/maillist.html
>
>If you have a problem with the JDE, please use JDE->Help->Submit Problem
>Report to prepare your query. This will insure that you include all
>information that may be required to solve your problem.