Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8253438

Add String::encodeEscapes

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Unresolved
    • Icon: P3 P3
    • None
    • None
    • core-libs
    • None

      The javac compiler has some code like this:

      /**
           * Escapes each character in a string that has an escape sequence or
           * is non-printable ASCII. Leaves non-ASCII characters alone.
           */
          public static String quote(String s) {
              StringBuilder buf = new StringBuilder();
              for (int i = 0; i < s.length(); i++) {
                  buf.append(quote(s.charAt(i)));
              }
              return buf.toString();
          }
        /**
           * Escapes a character if it has an escape sequence or is
           * non-printable ASCII. Leaves non-ASCII characters alone.
           */
          public static String quote(char ch) {
              switch (ch) {
              case '\b': return "\\b";
              case '\f': return "\\f";
              case '\n': return "\\n";
              case '\r': return "\\r";
              case '\t': return "\\t";
              case '\'': return "\\'";
              case '\"': return "\\\"";
              case '\\': return "\\\\";
              default:
                  return (isPrintableAscii(ch))
                      ? String.valueOf(ch)
                      : String.format("\\u%04x", (int) ch);
              }
          }
          /**
           * Is a character printable ASCII?
           */
          private static boolean isPrintableAscii(char ch) {
              return ch >= ' ' && ch <= '~';
          }

      This code is used to "quote" strings which comes from user code, and need to be rendered exactly as they have been typed by the user.

      Now that the Java SE API has the String::translateEscapes methods, it might be perhaps a good idea to make the internal javac functionality more officially supported (since it seems to be the reverse of what the newly added String method does?).

            smarks Stuart Marks
            mcimadamore Maurizio Cimadamore
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: