trim()
is a StringUtils
class which removes the control characters from both ends of the input string. 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;
The syntax of the trim()
method is as follows:
public static String trim(final String str)
The trim()
method takes the following parameter:
final String str
: The string to trim.This method returns trimmed string.
The method returns null
if the input string is null
.
The code below shows how you can use the trim()
method in Java:
import org.apache.commons.lang3.StringUtils;public class Main {public static void main(String[] args) {// Example 1String s = "\n hellO-EDUcative \r\r\n";System.out.printf("The output of StringUtils.trim() for the string - '%s' is '%s'", s, StringUtils.trim(s));System.out.println();// Example 2s = "";System.out.printf("The output of StringUtils.trim() for the string - '%s' is '%s'", s, StringUtils.trim(s));System.out.println();// Example 3s = null;System.out.printf("The output of StringUtils.trim() for the string - '%s' is '%s'", s, StringUtils.trim(s));System.out.println();}}
The output of the code will be as follows:
The output of StringUtils.trim() for the string - '
hellO-EDUcative
' is 'hellO-EDUcative'
The output of StringUtils.trim() for the string - '' is ''
The output of StringUtils.trim() for the string - 'null' is 'null'
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 `` as the input string is empty.
string = null
The method returns null
as the input string is null
.
Free Resources