Java String Quote quoteTo(CharSequence cs, StringBuilder target)

Here you can find the source of quoteTo(CharSequence cs, StringBuilder target)

Description

Quotes the given string as Java string literal style, and puts it into the given buffer.

License

Apache License

Parameter

Parameter Description
cs the source string
target the destination buffer

Declaration

public static void quoteTo(CharSequence cs, StringBuilder target) 

Method Source Code

//package com.java2s;
/**// w w w . jav  a 2 s. co  m
 * Copyright 2011-2017 Asakusa Framework Team.
 *
 * 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 {
    private static final char[] ASCII_SPECIAL_ESCAPE = new char[128];

    /**
     * Quotes the given string as Java string literal style, and puts it into the given buffer.
     * @param cs the source string
     * @param target the destination buffer
     */
    public static void quoteTo(CharSequence cs, StringBuilder target) {
        target.append('"');
        for (int i = 0, n = cs.length(); i < n; i++) {
            char c = cs.charAt(i);
            if (c <= 0x7f && ASCII_SPECIAL_ESCAPE[c] != 0) {
                target.append('\\');
                target.append(ASCII_SPECIAL_ESCAPE[c]);
            } else if (Character.isISOControl(c) || Character.isDefined(c) == false
                    || Character.isLowSurrogate(c)) {
                target.append(String.format("\\u%04x", (int) c)); //$NON-NLS-1$
            } else if (Character.isHighSurrogate(c)) {
                if (i + 1 < n) {
                    char next = cs.charAt(i + 1);
                    if (Character.isLowSurrogate(next)) {
                        target.append(c);
                        target.append(next);
                        i++;
                        continue;
                    }
                }
                target.append(String.format("\\u%04x", (int) c)); //$NON-NLS-1$
            } else {
                target.append(c);
            }
        }
        target.append('"');
    }
}

Related

  1. quoteStringSQL(String s)
  2. quoteStringSQL(String s)
  3. quoteStringValue(String value)
  4. quoteText(String text)
  5. quoteText(String textToQuote, boolean sbAppend)
  6. quoteTokenize(String clientResponse)
  7. QuoteValue(String str)
  8. quoteValue(String value)
  9. QuoteValueIfNeeded(String str)