Java String Quote quote(String text)

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

Description

quote

License

Apache License

Parameter

Parameter Description
text a parameter

Declaration

public static String quote(String text) 

Method Source Code

//package com.java2s;
/*//from  w ww .ja va  2s . c  o  m
 * Copyright (C) IBM Corp. 2008.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

public class Main {
    public static char[] hex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    /**
     * @param text
     * @return
     */
    public static String quote(String text) {
        StringBuilder buf = new StringBuilder();
        buf.append("\"");
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            switch (c) {
            case '\'':
                buf.append("\\'");
                break;
            case '\"':
                buf.append("\\\"");
                break;
            case '\\':
                buf.append("\\\\");
                break;
            case '\b':
                buf.append("\\b");
                break;
            case '\f':
                buf.append("\\f");
                break;
            case '\n':
                buf.append("\\n");
                break;
            case '\r':
                buf.append("\\r");
                break;
            case '\t':
                buf.append("\\t");
                break;
            default:
                if (Character.isISOControl(c)) {
                    buf.append("\\u");
                    buf.append(hex[((c & 0xf000) >>> 12)]);
                    buf.append(hex[((c & 0x0f00) >>> 8)]);
                    buf.append(hex[((c & 0x00f0) >>> 4)]);
                    buf.append(hex[(c & 0x000f)]);
                } else {
                    buf.append(c);
                }
            }
        }
        buf.append("\"");
        return buf.toString();
    }
}

Related

  1. quote(String text)
  2. quote(String text)
  3. quote(String text)
  4. quote(String text)
  5. quote(String text)
  6. quote(String text, String quote)
  7. quote(String toQuote, String specials, char quoteChar)
  8. quote(String txt)
  9. quote(String val)