Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I use the following two methods, toPrintable to convert the original string to a printable string, fromPrintable to convert it back.</p> <p>I included the percent sign in the conversion because sometimes I may want to use the converted string as a part of a format string and this prevents the original percent signs getting confused with the formatting percent signs.</p> <pre><code>/** * Converts a string containing control characters to a printable string. * Control characters are replaced by \hh, were hh is the hexadecimal * representation. The backslash and percent sign are also converted to * hexadecimal. * * @param raw * The input string to be converted. * * @return a string representing this instance. */ public static String toPrintable(final String raw) { final StringBuilder sb = new StringBuilder(); if (raw == null) { return ""; } for (final char c : raw.toCharArray()) { if ((c &lt;= 31) || (c == 127) || (c == '\\') || (c == '%')) { sb.append(String.format("\\%02X", (int) c)); } else { sb.append(c); } } /* * If the last character is a space, convert it to hexadecimal, to avoid * loosing it. */ if (raw.endsWith(" ")) { sb.setLength(sb.length() - 1); sb.append("\\20"); } return sb.toString(); } /** * Converts a string containing coded control characters to the original * string. Control characters are represented by \hh, were hh is the * hexadecimal representation. The backslash is also represented as * hexadecimal. * * @param t * The converted string to be restored. * @return The original string. */ public static String fromPrintable(final String t) { final StringBuilder sb = new StringBuilder(); final int tLength = t.length(); boolean error = false; for (int i = 0; i &lt; tLength; i++) { if (t.charAt(i) == '\\') { if ((i + 1) &lt; tLength) { if (t.charAt(i + 1) == '\\') { sb.append(t.charAt(i++)); } else { if (i &lt; (tLength - 2)) { final int v1 = validHexDigits.indexOf(t .charAt(i + 1)); final int v2 = validHexDigits.indexOf(t .charAt(i + 2)); i += 2; if ((v1 &lt; 0) || (v2 &lt; 0)) { error = true; } else { final char cc = (char) ((validHexValues[v1] &lt;&lt; 4) + validHexValues[v2]); sb.append(cc); } } else { error = true; } } } else { error = true; } } else { sb.append(t.charAt(i)); } } if (error) { log.warn("fromPrintable: Invalid input [%s]", t); } return sb.toString(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload