Java String Substritute substitute(String in, String find, String newString)

Here you can find the source of substitute(String in, String find, String newString)

Description

substitute returns a string in which 'find' is substituted by 'newString'

License

Open Source License

Parameter

Parameter Description
in String to edit
find string to match
newString string to substitude for find

Return

The edited string

Declaration

public static String substitute(String in, String find, String newString) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from  w w  w .j a va  2 s  .co m
     * <p>
     * substitute returns a string in which 'find' is substituted by 'newString'
     *
     * @param in String to edit
     * @param find string to match
     * @param newString string to substitude for find
     * @return The edited string
     */
    public static String substitute(String in, String find, String newString) {
        // when either of the strings are null, return the original string
        if (in == null || find == null || newString == null)
            return in;

        char[] working = in.toCharArray();
        StringBuffer stringBuffer = new StringBuffer();

        // when the find string could not be found, return the original string
        int startindex = in.indexOf(find);
        if (startindex < 0)
            return in;

        int currindex = 0;
        while (startindex > -1) {
            for (int i = currindex; i < startindex; i++) {
                stringBuffer.append(working[i]);
            } // for
            currindex = startindex;
            stringBuffer.append(newString);
            currindex += find.length();
            startindex = in.indexOf(find, currindex);
        } // while

        for (int i = currindex; i < working.length; i++) {
            stringBuffer.append(working[i]);
        } // for

        return stringBuffer.toString();
    }
}

Related

  1. substitute(final String input, final String pattern, final String sub)
  2. substitute(String original, String match, String subst)
  3. substitute(String s, String from, String to)
  4. substitute(String str, CharSequence... substitutionSeqs)
  5. substitute(String str, String from, String to)