trimToNull()
is a StringUtils
class that is used to remove the control characters from both ends of the input string.
null
if the input string is null
.null
if the input string results in an empty string after the trim operation.This method internally uses the trim method of the
String
class.
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 trimToNull(final String str)
final String str
: The string to trim.
This method returns a trimmed string.
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.trimToNull() for the string - '%s' is '%s'", s, StringUtils.trimToNull(s));System.out.println();s = "";System.out.printf("The output of StringUtils.trimToNull() for the string - '%s' is '%s'", s, StringUtils.trimToNull(s));System.out.println();s = null;System.out.printf("The output of StringUtils.trimToNull() for the string - '%s' is '%s'", s, StringUtils.trimToNull(s));System.out.println();}}
string = " hellO-EDUcative "
The method returns hellO-EDUcative
after removing the newline, carriage return, and space characters from the input string.
string = ""
The method returns null
as the input string is empty.
string = null
The method returns null
as the input string is null
.
The output of the code will be as follows.
The output of StringUtils.trimToNull() for the string - '
hellO-EDUcative
' is 'hellO-EDUcative'
The output of StringUtils.trimToNull() for the string - '' is 'null'
The output of StringUtils.trimToNull() for the string - 'null' is 'null'
Free Resources