Java String Quote quote(String string)

Here you can find the source of quote(String string)

Description

quote

License

LGPL

Declaration

public static String quote(String string) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

public class Main {
    public static String quote(String string) {
        if (string == null || string.length() == 0) {
            return "\"\"";
        }/* w w w  . j  av  a2s  . c o  m*/

        char c = 0;
        int i;
        int len = string.length();
        StringBuilder sb = new StringBuilder(len + 4);
        String t;

        sb.append('"');
        for (i = 0; i < len; i += 1) {
            c = string.charAt(i);
            switch (c) {
            case '\\':
            case '"':
                sb.append('\\');
                sb.append(c);
                break;
            case '/':
                // if (b == '<') {
                sb.append('\\');
                // }
                sb.append(c);
                break;
            case '\b':
                sb.append("\\b");
                break;
            case '\t':
                sb.append("\\t");
                break;
            case '\n':
                sb.append("\\n");
                break;
            case '\f':
                sb.append("\\f");
                break;
            case '\r':
                sb.append("\\r");
                break;
            default:
                if (c < ' ') {
                    t = "000" + Integer.toHexString(c);
                    sb.append("\\u" + t.substring(t.length() - 4));
                } else {
                    sb.append(c);
                }
            }
        }
        sb.append('"');
        return sb.toString();
    }
}

Related

  1. quote(String str)
  2. quote(String str)
  3. quote(String str, char c)
  4. quote(String str, String quoteChar)
  5. quote(String str, StringBuffer out)
  6. quote(String string)
  7. quote(String string)
  8. quote(String string)
  9. quote(String string)