This post will discuss how to remove a substring from a string in Java.

To remove a substring from a string in Java, we can use one of the following methods:

1. Using String.replace() method

The replace() method is a built-in method of the String class in Java that can be used to remove or replace a substring in a string. The method takes two parameters: the old substring that we want to replace, and the new substring that we want to insert. The replace() method will then replace all occurrences of the substring with the replacement string and returns a new string with the replacement. It can be used to remove a substring by replacing the substring with an empty string. For example, the following code calls the replace() method on the original string with the substring to be removed and the empty string as arguments.

Download  Run Code

2. Using Apache Commons Lang

We can also leverage Apache Commons Lang to remove or replace a substring from a string in Java. The StringUtils class provides various methods for string manipulation. We can use the StringUtils.remove() method to removes all occurrences of a substring from within the source string. We can use it like this:

Download Code

 
The StringUtils class also provides the replace() method that replaces all occurrences of a substring within another string with a new string. This method can also be used to remove a substring by replacing it with an empty string. Here’s an example:

Download Code

3. Using String.replaceFirst() method

All the above methods replaces any substring match in the string, not just the first occurrence. To replace only the first occurrence of a substring, we can use the String.replaceFirst() method instead. This method takes two parameters: a regular expression that matches the substring to be replaced, and the replacement string. The replaceFirst() method will then replace only the first occurrence of the substring that matches the regular expression with the replacement string. We can use this method to remove a substring by replacing it with an empty string. For instance:

Download  Run Code

4. Using String.replaceAll() method

To use a regular expression to match the substring, we can use the replaceAll() method of the String class instead. This method is similar to the replaceFirst() method, but it replaces all occurrences of the regular expression with the string in the original string. Here is a sample code that demonstrates this:

Download  Run Code

That’s all about removing a substring from a string in Java.