Java String Quote quoteString(String s)

Here you can find the source of quoteString(String s)

Description

Return a proper quoted string if the string contains the delimiter character

License

Apache License

Parameter

Parameter Description
s a parameter

Declaration

public static String quoteString(String s) 

Method Source Code

//package com.java2s;
/*//w w w . ja  v a 2s . c om
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 final String DELIMETER = ",";
    public static final String QUOTE = "\"";

    /**
     * Return a proper quoted string if the string contains the delimiter character
     * @param s
     * @return
     */
    public static String quoteString(String s) {
        return quoteString(s, DELIMETER);
    }

    /**
    * Return a proper quoted string if the string contains the delimiter character
    * @param s
    * @return
    */
    public static String quoteString(String s, String delimiter) {
        if (isQuoted(s, delimiter)) {
            return s;
        } else {
            return QUOTE + s.replaceAll(QUOTE, QUOTE + QUOTE) + QUOTE;
        }
    }

    private static boolean isQuoted(String s, String delimiter) {
        //Check if we need quotes
        if (s.contains(delimiter)) {
            //Check if its already quoted
            s = s.replaceAll("\"\"", "");
            return (s.substring(0, 1).equals(QUOTE) && s.subSequence(s.length() - 1, s.length()).equals(QUOTE));
        }
        //no delimiters present, so already in proper form
        return true;
    }

    private static boolean isQuoted(String s) {
        return isQuoted(s, DELIMETER);
    }
}

Related

  1. quoteString(final String text)
  2. quoteString(String arg)
  3. quoteString(String aTarget, String aPrefix, String aSuffix)
  4. quoteString(String in)
  5. quoteString(String quoted, String quoteFlag)
  6. quoteString(String s)
  7. quoteString(String s)
  8. quoteString(String s)
  9. quoteString(String s)