What is StringUtils.remove() in Java?
remove() is a StringUtils that removes all occurrences of a substring from within the source string. The comparison of the substring with the source string is case-sensitive in nature.
- An empty source string returns the empty string.
- An empty remove string returns the source string.
- A
nullsource string returns anull. - A
nullremove string returns the source string.
How to import StringUtils
The definition of StringUtils is in the Apache Commons Lang package. We can add this package to the Maven project by adding the following dependency to the pom.xml file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, we can refer to the Maven Repository.
We can import the StringUtils class as follows:
import org.apache.commons.lang3.StringUtils;
Syntax
public static String remove(final String str, final String remove)
Parameters
final String str: It is the source string to search.final String remove: It is the string to search and remove.
Return value
This method returns the substring with the string removed, if found.
Code
import org.apache.commons.lang3.StringUtils;public class Main{public static void main( String args[] ) {// Example 1String sourceString = "hello-educative-hello-educative";String removalString = "educat";System.out.printf("StringUtils.remove(%s, %s) = %s", sourceString, removalString, StringUtils.remove(sourceString, removalString));System.out.println();// Example 2sourceString = "hello-educative-hello-educative";removalString = "oll";System.out.printf("StringUtils.remove(%s, %s) = %s", sourceString, removalString, StringUtils.remove(sourceString, removalString));System.out.println();}}
Example 1
Source String = "hello-educative-hello-educative"Removal String = "educat"
The method returns hello-ive-hello-ive and removes all the occurrences of the removal string from the source string.
Example 2
Source String = "hello-educative-hello-educative"Removal String = "oll"
The method returns hello-educative-hello-educative that is the source string. This is because the removal string is not present in the source string.
Output
The output of the code is as follows:
StringUtils.remove(hello-educative-hello-educative, educat) = hello-ive-hello-ive
StringUtils.remove(hello-educative-hello-educative, oll) = hello-educative-hello-educative
Free Resources
- undefined by undefined
- undefined by undefined