How to trim leading and trailing whitespaces in String in Java
1 Answer
7 years ago by Divya
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 + "|");
}
}
7 years ago by Karthik Divi