What is StringUtils.left() in Java?
left() is a StringUtils class which is used to get the specified number of leftmost characters of a 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 left(String str, int len)
Parameters
str: The string to get the leftmost characters from.len: The length of the leftmost characters to extract from the string.
Return value
-
This method returns the leftmost characters of the string.
-
If
lenis negative, then an empty string is returned. -
If
strisnullor the value oflenis not available, then an empty string is returned.
Code
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();}}
Output
The output of the code is as follows:
StringUtils.left('hello-educative', 5) = 'hello'
StringUtils.left('hello-educative', -1) = ''
Explanation
Example 1
str="hello-educative"len=5
The method returns "hello" which is the leftmost substring of the given string with length 5.
Example 2
str="hello-educative"len=-1
The method returns "", an empty string, as the length value is negative.
Free Resources
- undefined by undefined
- undefined by undefined