Java String Quote quote(StringBuilder buf, String str)

Here you can find the source of quote(StringBuilder buf, String str)

Description

Simple quote of a string, escaping where needed.

License

Open Source License

Parameter

Parameter Description
buf the StringBuilder to append to
str the string to quote

Declaration

public static void quote(StringBuilder buf, String str) 

Method Source Code

//package com.java2s;
//  are made available under the terms of the Eclipse Public License v1.0

public class Main {
    private static final char UNICODE_TAG = 0xFFFF;
    private static final char[] escapes = new char[32];

    /**//from  ww  w.  ja va  2  s  .  co  m
     * Simple quote of a string, escaping where needed.
     * 
     * @param buf
     *            the StringBuilder to append to
     * @param str
     *            the string to quote
     */
    public static void quote(StringBuilder buf, String str) {
        buf.append('"');
        escape(buf, str);
        buf.append('"');
    }

    public static void escape(StringBuilder buf, String str) {
        for (char c : str.toCharArray()) {
            if (c >= 32) {
                // non special character
                if ((c == '"') || (c == '\\')) {
                    buf.append('\\');
                }
                buf.append(c);
            } else {
                // special characters, requiring escaping
                char escaped = escapes[c];

                // is this a unicode escape?
                if (escaped == UNICODE_TAG) {
                    buf.append("\\u00");
                    if (c < 0x10) {
                        buf.append('0');
                    }
                    buf.append(Integer.toString(c, 16)); // hex
                } else {
                    // normal escape
                    buf.append('\\').append(escaped);
                }
            }
        }
    }
}

Related

  1. quote(String val, char quote)
  2. quote(String value)
  3. quote(String value)
  4. quote(String value)
  5. quote(String value)
  6. quote(StringBuilder sb, String str)
  7. quote4CMDLine(String str)
  8. quoteAndClean(String str)
  9. quoteAndEscape(String str)