Strip Leading and Trailing Spaces From Java String

Tyler DeWitt picture Tyler DeWitt · Jul 11, 2011 · Viewed 423.4k times · Source

Is there a convenience method to strip any leading or trailing spaces from a Java String?

Something like:

String myString = "  keep this  ";
String stripppedString = myString.strip();
System.out.println("no spaces:" + strippedString);

Result:

no spaces:keep this

myString.replace(" ","") would replace the space between keep and this.

Answer

woliveirajr picture woliveirajr · Jul 11, 2011

You can try the trim() method.

String newString = oldString.trim();

Take a look at javadocs