Here you can find the source of substitute(String str, String source, String target)
Parameter | Description |
---|---|
str | the base string |
source | the substring to look for |
target | the replacement string to use |
public static String substitute(String str, String source, String target)
//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); } }