Java Java String Format toJavaString(String buf)

Here you can find the source of toJavaString(String buf)

Description

Escape characters unallowed in the Java source files.

License

Open Source License

Declaration

public static String toJavaString(String buf) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*  w  w  w .j  a  v  a  2s.  c  o  m*/
     * Escape characters unallowed in the Java source files.
     */
    public static String toJavaString(String buf) {
        return escape(buf, "\\u");
    }

    private static String escape(String buf, String hexEscape) {
        int len = buf.length();

        StringBuffer result = new StringBuffer(len);

        result.append('\"');
        for (int i = 0; i < len; i++) {
            char ch = buf.charAt(i);
            int esc = "\r\t\n\"\\".indexOf(ch);
            if (esc != -1) {
                result.append('\\');
                result.append("rtn\"\\".charAt(esc));
            } else if (ch < 0x20 || ch >= 0x80) {
                // non-ascii character. Print as \\uXXXX
                result.append(hexEscape);
                result.append(Integer.toHexString((ch >> 12) & 15));
                result.append(Integer.toHexString((ch >> 8) & 15));
                result.append(Integer.toHexString((ch >> 4) & 15));
                result.append(Integer.toHexString((ch >> 0) & 15));
            } else {
                // printable ascii character
                result.append(ch);
            }
            //            result.append(',');  debug
        }
        result.append('\"');

        return result.toString();
    }
}

Related

  1. toJavaScriptSafeString(String content)
  2. toJavaSecs(long secs)
  3. toJavaSourceType(String type)
  4. toJavaStaticIdentifier(String string)
  5. toJavaString(final String s)
  6. toJavaString(String text)
  7. toJavaTime(double time)
  8. toJavaTypeIdentifier(String string)
  9. toJavaTypeName(String edmTypeName)