是否有一种方便的方法可以从Java String中删除任何前导或尾随空格?
类似的东西:
String myString = " keep this ";
String stripppedString = myString.strip();
System.out.println("no spaces:" + strippedString);
结果:
no spaces:keep this
myString.replace(" ","")
会替换keep和this之间的空格。
由于
答案 0 :(得分:569)
答案 1 :(得分:76)
使用String#trim()
方法或String allRemoved = myString.replaceAll("^\\s+|\\s+$", "")
修剪结尾。
左侧修剪:
String leftRemoved = myString.replaceAll("^\\s+", "");
对于正确的修剪:
String rightRemoved = myString.replaceAll("\\s+$", "");
答案 2 :(得分:30)
来自docs:
String.trim();
答案 3 :(得分:15)
trim()是您的选择,但如果您想使用replace
方法 - 可能更灵活,您可以尝试以下方法:
String stripppedString = myString.replaceAll("(^ )|( $)", "");
答案 4 :(得分:2)
现在使用java-11,您可以使用 String.strip
API返回一个值为该字符串的字符串,并删除所有前导和尾随空格。相同的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"
答案 5 :(得分:0)
要修剪特定字符,可以使用:
ArrayList
此处将删除开头和结尾的空格和逗号。
答案 6 :(得分:0)
s.strip()。
s.trim()您可以使用。