In the StringUtils class, we have the methods stripStart() and stripEnd(). They remove leading and trailing characters respectively.
We can eliminate the leading and trailing spaces of a string in Java with the help of trim(). trim() method is defined under the String class of java.
Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.
Using String strip() APIs – Java 11 isWhitespace(char) method to determine a white space character. String strip() – returns a string whose value is given string, with all leading and trailing white space removed. Please note that String. trim() method also produces the same result.
You can try the trim() method.
String newString = oldString.trim();
Take a look at javadocs
Use String#trim()
method or String allRemoved = myString.replaceAll("^\\s+|\\s+$", "")
for trim both the end.
For left trim:
String leftRemoved = myString.replaceAll("^\\s+", "");
For right trim:
String rightRemoved = myString.replaceAll("\\s+$", "");
From the docs:
String.trim();
trim() is your choice, but if you want to use replace
method -- which might be more flexiable, you can try the following:
String stripppedString = myString.replaceAll("(^ )|( $)", "");
With Java-11 and above, 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 :
/**
* Returns a string whose value is this string, with all leading
* and trailing {@link Character#isWhitespace(int) white space}
* removed.
* <p>
* If this {@code String} object represents an empty string,
* or if all code points in this string are
* {@link Character#isWhitespace(int) white space}, then an empty string
* is returned.
* <p>
* Otherwise, returns a substring of this string beginning with the first
* code point that is not a {@link Character#isWhitespace(int) white space}
* up to and including the last code point that is not a
* {@link Character#isWhitespace(int) white space}.
* <p>
* This method may be used to strip
* {@link Character#isWhitespace(int) white space} from
* the beginning and end of a string.
*
* @return a string whose value is this string, with all leading
* and trailing white space removed
*
* @see Character#isWhitespace(int)
*
* @since 11
*/
public String strip()
The sample cases for these could be:--
System.out.println(" leading".strip()); // prints "leading"
System.out.println("trailing ".strip()); // prints "trailing"
System.out.println(" keep this ".strip()); // prints "keep this"
To trim specific char, you can use:
String s = s.replaceAll("^(,|\\s)*|(,|\\s)*$", "")
Here will strip leading and trailing space and comma.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With