Skip to content
Advertisement

Strip Leading and Trailing Spaces From Java String

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.

Advertisement

Answer

You can try the trim() method.

String newString = oldString.trim();

Take a look at javadocs

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement