What is StringUtils.trimToEmpty() in Java?
trimToEmpty() is a StringUtils class that is used to remove control characters from both ends of the input string.
- The method returns an empty string if the input string is
null. - The method returns an empty string if the input string results in an empty string after the trim operation.
This method internally uses the trim method of the
Stringclass.
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-langpackage, refer to the Maven Repository.
You can import the StringUtils class as follows.
import org.apache.commons.lang3.StringUtils;
Syntax
public static String trimToEmpty(final String str)
Parameters
final String str: The string to trim.
Return value
This method returns trimmed string.
Code
import org.apache.commons.lang3.StringUtils;public class Main {public static void main(String[] args) {String s = "\n hellO-EDUcative \r\r\n";System.out.printf("The output of StringUtils.trimToEmpty() for the string - '%s' is '%s'", s, StringUtils.trimToEmpty(s));System.out.println();s = "";System.out.printf("The output of StringUtils.trimToEmpty() for the string - '%s' is '%s'", s, StringUtils.trimToEmpty(s));System.out.println();s = null;System.out.printf("The output of StringUtils.trimToEmpty() for the string - '%s' is '%s'", s, StringUtils.trimToEmpty(s));System.out.println();}}
Example 1
- string =
" hellO-EDUcative "
The method returns hellO-EDUcative after removing the newline, carriage return, and space characters from the input string.
Example 2
- string =
""
The method returns '' as the input string is empty.
Example 3
- string =
null
The method returns '' as the input string is null.
Output
The output of the code will be as follows:
The output of StringUtils.trimToEmpty() for the string - '
hellO-EDUcative
' is 'hellO-EDUcative'
The output of StringUtils.trimToEmpty() for the string - '' is ''
The output of StringUtils.trimToEmpty() for the string - 'null' is ''
Free Resources
- undefined by undefined