stripToEmpty()
is a static method of StringUtils
that is used to strip all the leading and trailing whitespace from a string.
null
reference.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;
public static String stripToEmpty(final String str)
final String str
: The string to be stripped.
The stripToEmpty
method returns a new string with all the leading and trailing whitespace removed from the input string.
" 543234asfg "
The method returns 543234asfg
, with all the leading and trailing whitespaces removed from the input string.
""
The method returns ''
because the input string is empty.
null
The method returns ''
because the string points to a null
reference." "
The method returns ''
, with all the leading and trailing whitespaces removed from the input string.
" 543234 asfg "
The method returns 543234 asfg
, with all the leading and trailing whitespaces removed from the input string.
import org.apache.commons.lang3.StringUtils;public class Main {public static void main(String[] args) {String s = " 543234asfg ";System.out.printf("The output of StringUtils.stripToEmpty() for the string - '%s' is '%s'", s, StringUtils.stripToEmpty(s));System.out.println();s = "";System.out.printf("The output of StringUtils.stripToEmpty() for the string - '%s' is '%s'", s, StringUtils.stripToEmpty(s));System.out.println();s = null;System.out.printf("The output of StringUtils.stripToEmpty() for the string - '%s' is '%s'", s, StringUtils.stripToEmpty(s));System.out.println();s = " ";System.out.printf("The output of StringUtils.stripStart() for the string - '%s' is '%s'", s, StringUtils.stripToEmpty(s));System.out.println();s = " 543234 asfg ";System.out.printf("The output of StringUtils.stripToEmpty() for the string - '%s' is '%s'", s, StringUtils.stripToEmpty(s));System.out.println();}}
The output of the code will be as follows:
The output of StringUtils.stripToEmpty() for the string - ' 543234asfg ' is '543234asfg'
The output of StringUtils.stripToEmpty() for the string - '' is ''
The output of StringUtils.stripToEmpty() for the string - 'null' is ''
The output of StringUtils.stripStart() for the string - ' ' is ''
The output of StringUtils.stripToEmpty() for the string - ' 543234 asfg ' is '543234 asfg'