How to trim leading and trailing whitespaces in String in Java

Views: 143 Ask New Question


On By

1 Answer


You can use the trim() utility method on java.lang.String class to trim leading and trailing whitespaces, Following code shows you how to use the trim() method on String

String stringWithSpaces = " foo boo     ";
String stringWithoutSpaces = stringWithSpaces.trim();

Following is the complete Java program that shows usage of trim()

public class TrimWhiteSpaces {

    public static void main(String[] args) {

        String stringWithSpaces = " foo boo     ";
        System.out.println("|" + stringWithSpaces + "|");

        // Trim spaces
        String stringWithoutSpaces = stringWithSpaces.trim();
        System.out.println("|" + stringWithoutSpaces + "|");
    }

}
On By


Answer This Question