Java String Substritute substitute(String str, String source, String target)

Here you can find the source of substitute(String str, String source, String target)

Description

In a string, replace one substring with another.

License

Open Source License

Parameter

Parameter Description
str the base string
source the substring to look for
target the replacement string to use

Return

the original string, str, with its first instance of source replaced by target

Declaration

public static String substitute(String str, String source, String target) 

Method Source Code

//package com.java2s;
// it under the terms of the GNU General Public License as published by

public class Main {
    /**/*from w w w  . j  av  a2  s .c  om*/
       In a string, replace one substring with another.
        
       <p>If str contains source, return a new string with (the first
       occurrence of) source replaced by target.</p>
        
       <p>If str doesn't contain source (or str is the empty string),
       returns str.</p>
        
       <p>Think: str ~= s/source/target/</p>
        
       <p>This is like Java 1.4's String.replaceFirst() method; when I
       decide to drop support for Java 1.3, I can use that method
       instead.</p>
        
       @param str the base string
       @param source the substring to look for
       @param target the replacement string to use
       @return the original string, str, with its first instance of
       source replaced by target
    */
    public static String substitute(String str, String source, String target) {
        int index = str.indexOf(source);
        if (index == -1) // not present
            return str;
        int start = index, end = index + source.length();
        return str.substring(0, start) + target + str.substring(end);
    }
}

Related

  1. substitute(String in, String find, String newString)
  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)
  6. substitute(String str, String source, String target)
  7. substitute(String str, String variable, String value, int num)
  8. substitute(String string, String pattern, String replacement)
  9. substitute(String strSource, String strValue, String strBookmark)