Java examples for java.lang:String Unicode
Converts a string to the string literal representation.
//package com.java2s; public class Main { public static void main(String[] argv) { String str = "java2s.com"; System.out.println(convertToLiteral(str)); }/*from ww w. ja va2 s .c o m*/ /** Converts a string to the string literal representation. */ public final static String convertToLiteral(String str) { int i = 0; int l = str.length(); char c; String num; StringBuffer buf; int n; buf = new StringBuffer(l + 2); buf.append('"'); while (i < l) { c = str.charAt(i++); switch (c) { case '\n': buf.append("\\n"); break; case '\t': buf.append("\\t"); break; case '\b': buf.append("\\b"); break; case '\r': buf.append("\\r"); break; case '\f': buf.append("\\f"); break; case '\\': buf.append("\\\\"); break; case '"': buf.append("\\\""); break; default: if ((c < (char) 32) || (c > (char) 127)) { buf.append("\\u"); num = Integer.toOctalString((int) c); while (num.length() < 4) num = "0" + num; buf.append(num); } else { buf.append(c); } // end if } // end switch } // end while buf.append('"'); return buf.toString(); } }