Showing the source code view of a Java String

public class InspectString {
  public static String inspect(final String str) {
    String result = "\"";
    final char[] chs = str.toCharArray();
    for (int i = 0; i < chs.length; i++) {
      final char ch = chs[i];
      if      (ch >= 128) result += String.format("\\u%04x", (int) ch);
      else if (ch == '"') result += "\\\"";
      else if (ch >=  32) result += ch;
      else switch (ch) {
        case '\b':        result += "\\b"; break;
        case '\f':        result += "\\f"; break;
        case '\n':        result += "\\n"; break;
        case '\r':        result += "\\r"; break;
        case '\t':        result += "\\t"; break;
        default:        if (i == chs.length - 1)
                          result += String.format("\\%o", (int) ch);
                        else {
                          final char nextCh = chs[i + 1];
                          result += String.format((nextCh >= '0' && nextCh <= '9') ? "\\%03o" : "\\%o", (int) ch);
                        }
      }
    }
    result += "\"";
    return result;
  }
  
  public static final void main(final String[] args) {
    System.out.println(inspect("zomg\0\u28af!!! !!!.123\"'\n\n\t\r\b\1\0133\013\f"));
  }
}
Advertisements
This entry was posted in Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s