Java String Substritute substitute(String string, String pattern, String replacement)

Here you can find the source of substitute(String string, String pattern, String replacement)

Description

Replace all occurrences of pattern in the specified string with replacement.

License

Open Source License

Parameter

Parameter Description
string The string to edit.
pattern The string to replace.
replacement The string to replace it with.

Return

A new string with the specified replacements.

Declaration

public static String substitute(String string, String pattern, String replacement) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /** Replace all occurrences of <i>pattern</i> in the specified
     *  string with <i>replacement</i>.  Note that the pattern is NOT
     *  a regular expression, and that relative to the
     *  String.replaceAll() method in jdk1.4, this method is extremely
     *  slow.  This method does not work well with back slashes.
     *  @param string The string to edit.
     *  @param pattern The string to replace.
     *  @param replacement The string to replace it with.
     *  @return A new string with the specified replacements.
     *//*  ww  w  .j  a  v  a 2  s .  c o m*/
    public static String substitute(String string, String pattern, String replacement) {
        int start = string.indexOf(pattern);

        while (start != -1) {
            StringBuffer buffer = new StringBuffer(string);
            buffer.delete(start, start + pattern.length());
            buffer.insert(start, replacement);
            string = new String(buffer);
            start = string.indexOf(pattern, start + replacement.length());
        }

        return string;
    }
}

Related

  1. substitute(String str, CharSequence... substitutionSeqs)
  2. substitute(String str, String from, String to)
  3. substitute(String str, String source, String target)
  4. substitute(String str, String source, String target)
  5. substitute(String str, String variable, String value, int num)
  6. substitute(String strSource, String strValue, String strBookmark)
  7. substitute(String template, String[] values)
  8. substitute(String txt, String pattern, String sub)
  9. substituteAll(String regexp, String subst, String target)