Replaces every ' with '' in the given string. - Java java.lang

Java examples for java.lang:String Quote

Description

Replaces every ' with '' in the given string.

Demo Code

// All Rights Reserved.
//package com.java2s;

public class Main {
    /**//www . j  a v  a2 s  .c o m
     * Replaces every ' with '' in the given string. This is done so that the
     * SQL for Oracle text data can be entered that contains Single Quote.
     *
     * @param str Given string
     *
     * @return Modified string
     */
    public static String escapeSingleQuote(String str) {
        return replaceWith(str, "'", "''");
    }

    /**
     * Replace the given string part with given replace string.
     *
     * @param str Given string (eg "c:\rcn\a.txt;d:\db\mail.elm")
     * @param replace Separator (eg ";")
     * @param with Given string (eg "<BR>") with which to replace the 'replace'
     * string.
     *
     * @return eg "c:\rcn\a.txt<BR>d:\db\mail.elm"
     */
    public static String replaceWith(String str, String replace, String with) {
        // Return str if any string given is null OR the
        // replace string is empty one
        if (str == null || replace == null || with == null
                || replace.equals("")) {
            return str;
        }

        // Replace the given 'replace substring' from the given
        // string with the 'with substring'
        StringBuffer sb = new StringBuffer();
        int len = replace.length();
        int toIndex = 0;
        int fromIndex = 0;
        while (fromIndex != -1) {
            toIndex = str.indexOf(replace, fromIndex);
            if (toIndex != -1) {
                // Get the substring
                sb.append(str.substring(fromIndex, toIndex));
                sb.append(with);
                fromIndex = toIndex + len;
            } else {
                // Get the remainder of the string, if any
                if (fromIndex <= str.length()) {
                    sb.append(str.substring(fromIndex, str.length()));
                }
                fromIndex = toIndex;
            }
        }
        return sb.toString();
    }
}

Related Tutorials