Java String Quote quoteIfNotNull(String str)

Here you can find the source of quoteIfNotNull(String str)

Description

quote If Not Null

License

Open Source License

Declaration

public static String quoteIfNotNull(String str) 

Method Source Code

//package com.java2s;
//  in accordance with the terms of the license agreement accompanying it.

public class Main {
    public static String quoteIfNotNull(String str) {
        return str = (str != null) ? str = "'" + escapeApostrophe(str) + "'" : null;
    }// w  w  w  .j  av  a 2s.com

    public static String escapeApostrophe(String str) {
        if (str.indexOf("'") > -1) {
            return substitute(str, "'", "''");
        }
        return str;
    }

    /**
     * Simple string replace routine, return the same string with
     * all instances of from replaced with to
     **/
    public static String substitute(String str, String from, String to) {
        if (from == null || from.equals("") || to == null)
            return str;

        int index = str.indexOf(from);

        if (index == -1)
            return str;

        StringBuffer buf = new StringBuffer(str.length());
        int lastIndex = 0;

        while (index != -1) {
            buf.append(str.substring(lastIndex, index));
            buf.append(to);
            lastIndex = index + from.length();
            index = str.indexOf(from, lastIndex);
        }

        // add in last chunk
        buf.append(str.substring(lastIndex));

        return buf.toString();
    }
}

Related

  1. quoteIfNeeded(String id)
  2. quoteIfNeeded(String input)
  3. quoteIfNeeded(String source)
  4. quoteIfNeeded(String value)
  5. quoteIfNeeded(StringBuilder buf, String str, String delim)
  6. quoteIfNotNull(String text)
  7. quoteIfNotNull(StringBuilder sb, String val)
  8. quoteIfString(Object obj)
  9. quoteIfString(Object obj)