Replace String ExamplesUse replace, replaceFirst and replaceAll to swap strings, chars and CharSequences.
This page was last reviewed on Dec 3, 2021.
Replace. In Java programs we often need to modify strings before using them. We find that there are many forms of the replace() method.
Java method notes. With replaceFirst and replaceAll we specify what we want to replace. Powerful Regex-based methods are also available.
An example. 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.
Tip This replace call changes all characters with matching values, not just the first one. This is important to remember.
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); } }
CharSequence, Strings. We also can call replace() with CharSequence arguments. A CharSequence is an interface that is implemented by the String class. So we can replace Strings.
Tip This version of replace checks the entire 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."
So The substrings a100z, a200z and a300z are matched and replaced. But the substring b100z is not.
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 end. With the "$" metacharacter, we can match the end of a string. This allows us to use replaceFirst to replace an ending string.
Here The 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
Optimization. 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.
Here The first string contains HTML, so we call replace() on it. But the second string does not, so we skip it.
Tip This optimization depends on the data being processed in a program, and the exact logic. But it is sometimes worth doing.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 3, 2021 (simplify).
© 2007-2023 Sam Allen.