At Charles Hart's suggestion, I have decided to combine David Hay's
approach with Mark Gibson and Steve Haflich's idea of first testing whether
the string actually needs escaping. The result is a method that requires no
object allocation for strings that do not require escaping, which should be
the most common case. The result is below.

Thanks to David, Mark, Steve, and Charles for helping me with designing and
implementing this method.

BTW, all debugger output is going to pass through this filter, so making it
as efficient as possible is very worthwhile.

Regards,

Paul


  /**
   * Prefix \ escapes to all \ and " characters in a string so that
   * the quoted string can be printed rereadably. For efficiency,
   * if no such characters are found, the argument String itself
   * is returned.
   *
   * @param  str   String to be prefixed.
   * @return A String.
   *
   * @author David Hay
   * @author Mark Gibson
   * @author Steve Haflich
   * @author Charles Hart
   */
  public static String escapeString (String str) {

    int escCount = 0;
    int len = str.length();
    char c;

    // Count number of chars that need escaping.
    for (int i=0; i<len; i++) {
      c = str.charAt(i);
      if (c == '\\' || c == '\"')
        escCount++;
    }

    if (escCount > 0) {

      StringBuffer buf = new StringBuffer(str.length() + escCount);

      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();
    }  
    else 
      return str;
  }

Reply via email to