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.
null
source string returns a null
.null
remove string returns the source string.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;
public static String remove(final String str, final String remove)
final String str
: It is the source string to search.final String remove
: It is the string to search and remove.This method returns the substring with the string removed, if found.
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();}}
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.
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.
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