What is StringUtils.removeStart() in Java?

removeStart() is a staticthe methods in Java that can be called without creating an object of the class. method of the StringUtils class that is used to remove a substring only if the substring occurs at the beginning of a source string. Otherwise, the source string itself is returned. The matching is case-sensitive in nature.

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 removeStart(String str, String remove)

Parameters

  • str: The source string to search for the substring to be removed from.
  • remove: The string to search and remove from the source string.

Return value

This method returns the source string with the substring, remove, removed if found.

  • A null source string will return null.
  • An empty ("") source string will return the empty string.
  • A null search string will return the source string.

Code

import org.apache.commons.lang3.StringUtils;
public class Main{
public static void main( String args[] ) {
// Example 1
String sourceString = "hello-educative";
String removalString = "hello";
System.out.printf("StringUtils.removeStart(%s, %s) = %s", sourceString, removalString, StringUtils.removeStart(sourceString, removalString));
System.out.println();
// Example 2
sourceString = "hello-educative";
removalString = "educat";
System.out.printf("StringUtils.removeStart(%s, %s) = %s", sourceString, removalString, StringUtils.removeStart(sourceString, removalString));
System.out.println();
}
}

Output

The output of the code will be as follows:


StringUtils.removeStart(hello-educative, hello) = -educative
StringUtils.removeStart(hello-educative, educat) = hello-educative

Explanation

Example 1

  • sourceString = "hello-educative"
  • removalString = "hello"

The method returns "-educative" because the source string starts with the removal string, and the removal string is removed from the source string.

Example 2

  • sourceString = "hello-educative"
  • removalString = "educat"

The method returns "hello-educative", as the source string does not start with the removal string, and so the original source string is returned as-is.

Free Resources

Attributions:
  1. undefined by undefined
  2. undefined by undefined