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.
Thanks
With java-11 now you can make use of the
String.strip
API to return a string whose value is this string, with all leading and trailing whitespace removed. The javadoc for the same reads :The sample cases for these could be:--
From the docs:
Use
String#trim()
method orString allRemoved = myString.replaceAll("^\\s+|\\s+$", "")
for trim both the end.For left trim:
For right trim:
You can try the trim() method.
Take a look at javadocs
trim() is your choice, but if you want to use
replace
method -- which might be more flexiable, you can try the following: