In this tutorial, we're going to be looking at various means we can remove or replace part of a String in Java.
We'll explore removing and/or replacing a substring using a String API, then using a StringBuilder API and finally using the StringUtils class of Apache Commons library.
As a bonus, we'll also look into replacing an exact word using the String API and the Apache Commons RegExUtils class.
2. String API
One of the simplest and straightforward methods of replacing a substring is using the replace, replaceAll or replaceFirst of a String class.
The replace() method takes two arguments – target and replacement text:
String master = "Hello World Baeldung!"; String target = "Baeldung"; String replacement = "Java"; String processed = master.replace(target, replacement); assertTrue(processed.contains(replacement)); assertFalse(processed.contains(target));
The above snippet will yield this output:
Hello World Java!
If a regular expression is required in choosing the target, then the replaceAll() or replaceFirst() should be the method of choice. As their name implies, replaceAll() will replace every matched occurrence, while the replaceFirst() will replace the first matched occurrence:
String master2 = "Welcome to Baeldung, Hello World Baeldung"; String regexTarget = "(Baeldung)$"; String processed2 = master2.replaceAll(regexTarget, replacement); assertTrue(processed2.endsWith("Java"));
The value of processed2 will be:
Welcome to Baeldung, Hello World Java
It's because the regex supplied as regexTarget will only match the last occurrence of Baeldung. In all examples given above, we can use an empty replacement and it'll effectively remove a target from a master.
3. StringBuilder API
We can also manipulate text in Java using the StringBuilder class. The two methods here are delete() and replace().
We can construct an instance of a StringBuilder from an existing String and then use the methods mentioned to perform the String manipulation as desired:
String master = "Hello World Baeldung!"; String target = "Baeldung"; String replacement = "Java"; int startIndex = master.indexOf(target); int stopIndex = startIndex + target.length(); StringBuilder builder = new StringBuilder(master);
Now we can remove the target with the delete():
builder.delete(startIndex, stopIndex); assertFalse(builder.toString().contains(target));
We can as well use the replace() to update the master:
builder.replace(startIndex, stopIndex, replacement); assertTrue(builder.toString().contains(replacement));
One apparent difference between using the StringBuilder and the String API is that we've to get the start and the stop index of the target String ourselves.
4. StringUtils Class
Another method we'll consider is the Apache Commons library.
First, let's add the required dependency to our project:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.8.1</version> </dependency>
The latest version of the library can be found here.
The StringUtils class has methods for replacing a substring of a String:
String master = "Hello World Baeldung!"; String target = "Baeldung"; String replacement = "Java"; String processed = StringUtils.replace(master, target, replacement); assertTrue(processed.contains(replacement));
There is an overloaded variant of the replace() that takes an integer max parameter, which determines the number of occurrences to replace. We can also use the replaceIgnoreCase() if case-sensitivity is not a concern:
String master2 = "Hello World Baeldung!"; String target2 = "baeldung"; String processed2 = StringUtils.replaceIgnoreCase(master2, target2, replacement); assertFalse(processed2.contains(target));
5. Replacing Exact Words
In this last example, we'll learn how to replace an exact word inside a String.
The straightforward way to perform this replacement is using a regular expression with word boundaries.
The word boundary regular expression is \b. Enclosing the desired word inside this regular expression will only match exact occurrences.
First, let's see how to use this regular expression with the String API:
String sentence = "A car is not the same as a carriage, and some planes can carry cars inside them!"; String regexTarget = "\\bcar\\b"; String exactWordReplaced = sentence.replaceAll(regexTarget, "truck");
The exactWordReplaced string contains:
"A truck is not the same as a carriage, and some planes can carry cars inside them!"
Only the exact word will be replaced. Notice backward slash always needs to be escaped when working with regular expressions in Java.
An alternate way to do this replacement is using the RegExUtils class from the Apache Commons Library, which can be added as a dependency as we saw in the previous section:
String regexTarget = "\\bcar\\b"; String exactWordReplaced = RegExUtils.replaceAll(sentence, regexTarget, "truck");
While both methods will yield the same result, deciding which one should be used will depend on our specific scenario.
In conclusion, we've explored more than one way of removing and replacing a substring in Java. The best method to apply still largely depends on the current situation and context.
As usual, the complete source code is available over on Github.