What is StringUtils.removeEnd() in Java?
removeEnd() is a StringUtils which is used to remove a substring only if it is at the end of a source string, otherwise returns the source string. The matching is case-sensitive in nature.
- A
nullsource string will returnnull. - An empty ("") source string will return the empty string.
- A
nullsearch string will return the source string.
How to import StringUtils
The definition of StringUtils can be found in the Apache Commons Lang package, which we can add 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, refer to the Maven Repository.
You can import the StringUtils class as follows:
import org.apache.commons.lang3.StringUtils;
Syntax
public static String removeEnd(final String str, final String remove)
Parameters
final String str: The source string to search.final String remove: 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";String removalString = "cative";System.out.printf("StringUtils.removeEnd(%s, %s) = %s", sourceString, removalString, StringUtils.removeEnd(sourceString, removalString));System.out.println();// Example 2sourceString = "hello-educative";removalString = "educat";System.out.printf("StringUtils.removeEnd(%s, %s) = %s", sourceString, removalString, StringUtils.removeEnd(sourceString, removalString));System.out.println();}}
Example 1
Source String = "hello-educative"Removal String = "cative"
The method returns hello-edu as the source string ends with the removal string and the removal string is removed from the source string.
Example 2
Source String = "hello-educative"Removal String = "educat"
The method returns hello-educative as the source string does not end with the removal string and the source string is returned as-is.
Output
The output of the code will be as follows:
StringUtils.removeEnd(hello-educative, cative) = hello-edu
StringUtils.removeEnd(hello-educative, educat) = hello-educative
Free Resources
- undefined by undefined