Java String Quote quote(final CharSequence phrase)

Here you can find the source of quote(final CharSequence phrase)

Description

Quote the phrase from the given quote character.

License

Open Source License

Parameter

Parameter Description
phrase the given phrase to quote.

Return

the quoted phrase.

Declaration

public static CharSequence quote(final CharSequence phrase) 

Method Source Code

//package com.java2s;
/*****************************************************************
 Copyright 2006 by Dung Nguyen (dungnguyen@truthinet.com)

 Licensed under the iNet Solutions Corp.,;
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.truthinet.com/licenses//from   w w  w  .ja va2 s  .  c  o  m

 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 {
    /**
     * Quote the phrase from the given quote character.
     * 
     * <pre>
     * This implementation scan through the phrase and find the quote value, each quote value
     * will be replace with the '\\' character at the first quote.
     * </pre>
     * 
     * @param phrase the given phrase to quote.
     * 
     * @return the quoted phrase.
     */
    public static CharSequence quote(final CharSequence phrase) {
        int length = phrase.length();

        // hold the quoted phrase.
        final StringBuilder builder = new StringBuilder();
        builder.append('"');
        char ch = '\0';

        for (int index = 0; index < length; index++) {
            ch = phrase.charAt(index);
            if (ch == '\\') {
                builder.append("\\\\").append('\\')
                        .append(phrase.charAt(++index));
            } else if (ch == '"') {
                builder.append('\\').append('"');
            } else {
                builder.append(ch);
            }
        }
        builder.append('"');

        return builder.toString();
    }
}

Related

  1. quote(CharSequence cs)
  2. quote(CharSequence str)
  3. quote(CharSequence value)
  4. quote(final CharSequence original)
  5. quote(final String s)
  6. quote(final String str)
  7. quote(final String str)
  8. quote(final String str)