4 回答
TA贡献1835条经验 获得超7个赞
trim()是您的选择,但是如果您想使用replacemethod -可能更灵活,则可以尝试以下操作:
String stripppedString = myString.replaceAll("(^ )|( $)", "");
TA贡献2019条经验 获得超9个赞
现在,使用java-11,您可以利用String.stripAPI返回一个值为该字符串的字符串,并删除所有前导和尾随空格。相同的javadoc读取:
/**
* 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()
这些示例案例可能是:-
System.out.println(" leading".strip()); // prints "leading"
System.out.println("trailing ".strip()); // prints "trailing"
System.out.println(" keep this ".strip()); // prints "keep this"
添加回答
举报