left() is a StringUtils class which is used to get the specified number of leftmost characters of a string.
StringUtilsThe 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;
public static String left(String str, int len)
str: The string to get the leftmost characters from.len: The length of the leftmost characters to extract from the string.This method returns the leftmost characters of the string.
If len is negative, then an empty string is returned.
If str is null or the value of len is not available, then an empty string is returned.
import org.apache.commons.lang3.StringUtils;public class Main{public static void main(String[] args) {// Example 1String str = "hello-educative";int len = 5;System.out.printf("StringUtils.left('%s', %s) = '%s'", str, len, StringUtils.left(str, len));System.out.println();// Example 2len = -1;System.out.printf("StringUtils.left('%s', %s) = '%s'", str, len, StringUtils.left(str, len));System.out.println();}}
The output of the code is as follows:
StringUtils.left('hello-educative', 5) = 'hello'
StringUtils.left('hello-educative', -1) = ''
str = "hello-educative"len = 5The method returns "hello" which is the leftmost substring of the given string with length 5.
str = "hello-educative"len = -1The method returns "", an empty string, as the length value is negative.
Free Resources