Replace
In Java programs we often need to modify strings before using them. We find that there are many forms of the replace()
method.
With replaceFirst
and replaceAll
we specify what we want to replace. Powerful Regex
-based methods are also available.
Here we use the version of replace()
that replaces all instances of one char
value with another. So we change all "a" letters to the underscore "_" character.
public class Program { public static void main(String[] args) { String value = "Java"; // Replace letter with underscore. String result = value.replace('a', '_'); System.out.println(result); } }J_v_
CharSequence
, StringsWe also can call replace()
with CharSequence
arguments. A CharSequence
is an interface
that is implemented by the String
class
. So we can replace Strings.
string
for all possible replacements. It does not just replace the first one.public class Program { public static void main(String[] args) { String animals = "cat cat dog"; // Replace all CharSequences (strings) with another. String result = animals.replace("cat", "mouse"); System.out.println(result); } }mouse mouse dog
ReplaceFirst
This method only replaces the first occurrence of the string
found. We also can use Regex
with this method. Please see the replaceAll
example for tips on Regex
replacing.
public class Program { public static void main(String[] args) { String pets = "cat cat dog"; // Replace first instance of "cat". String result = pets.replaceFirst("cat", "bird"); System.out.println(result); } }bird cat dog
ReplaceAll
, Regex
This program uses a regular expression to replace all matches of a pattern with a string
. The "\d" codes mean "digit." We match 3 digits surrounded by "a" and "z."
public class Program { public static void main(String[] args) { String codes = "a100z a200z a300z b100z"; // Replace all matches with a string. String result = codes.replaceAll("a\\d\\d\\dz", "a---z"); System.out.println(result); } }a---z a---z a---z b100z
Replace
endWith the "$" metacharacter, we can match the end of a string
. This allows us to use replaceFirst
to replace an ending string
.
string
contains three "cats." We only replace the final, ending cat with a "dog" string
.public class Program { public static void main(String[] args) { String pets = "cat cat cat"; // Use metacharacter to ensure the replacement is at the end. String result = pets.replaceFirst("cat$", "dog"); System.out.println(result); } }cat cat dog
Sometimes we can use logic to avoid calling replace()
when it is not needed. If many strings do not need to be processed, indexOf()
or contains()
can help.
string
contains HTML, so we call replace()
on it. But the second string
does not, so we skip it.public class Program { public static String replaceIfNeeded(String value) { // Test the string to see if any of the replacements can succeed. if (value.contains("<span>")) { value = value.replace("<span><b>", "*"); value = value.replace("<span><i>", "/"); } if (value.contains("</span>")) { value = value.replace("</b></span>", "*"); value = value.replace("</i></span>", "/"); } return value; } public static void main(String[] args) { // ... All replace calls are used on this string. String result = replaceIfNeeded("<span><b>Cat</b></span>"); System.out.println(result); // ... No replace calls are needed. result = replaceIfNeeded("Dog"); System.out.println(result); } }*Cat* Dog
Regex
or string
Should we use a Regex
or a String
in replace? If only one constant pattern needs replacing, a String
is simpler. But if differences may occur, a Regex
is clearer.
StringBuilder
Replace
on StringBuilder
is different from the String
method. With StringBuilder
, we indicate a range with indexes, and then replace those characters with another string
.
With replace, we gain powerful ways to change Strings. Each time, a new String
is created. So all the data must be copied. With StringBuilder
this inefficiency is reduced.