How to Trim a String in Java?

Requirement:

Trim a string in Java and remove all spaces ( before and after the word). For example “    ght   ” should be trimmed to “ght”.

Download JAR files:

Download commons-lang3-3.1.jar file from Apache website for this example to work.

Java Program Code:

The Complete Java code to Trim a string is provided below:

import org.apache.commons.lang3.StringUtils; // to trim the string
public class trimString {    
    public static void main (String[] args) {
                        String myInput="   ght  ";
                        String newRepeatedString=StringUtils.trimToEmpty(myInput);
                        //This method trims the string
                        System.out.println("Input: " + myInput);
                        System.out.println("Trimmed : " + newRepeatedString);                   
    }
}

Example Output:


C:\Java\commons-lang3-3.1>javac -classpath .;commons-lang3-3.1.jar trimString.java
C:\Java\commons-lang3-3.1>java -classpath .;commons-lang3-3.1.jar trimString
Input:    ght
Trimmed : ght