是否有一个方便的方法从Java字符串剥离任何前导或尾随空格?

喜欢的东西:

String myString = "  keep this  ";
String stripppedString = myString.strip();
System.out.println("no spaces:" + strippedString);

结果:

no spaces:keep this

myString。Replace(" ","")将替换keep和this之间的空格。


当前回答

使用String#trim()方法或String allRemoved = myString。replaceAll(“^ \ \ s + | \ \ s + $ ", " ")的削减。

左内饰:

String leftRemoved = myString.replaceAll("^\\s+", "");

右内饰:

String rightRemoved = myString.replaceAll("\\s+$", "");

其他回答

在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"

您可以尝试trim()方法。

String newString = oldString.trim();

看一下javadocs

要修剪特定的字符,你可以使用:

String s = s.replaceAll("^(,|\\s)*|(,|\\s)*$", "")

这里将去掉开头和结尾的空格和逗号。

从文档中可以看出:

String.trim();

Trim()是你的选择,但如果你想使用replace方法——这可能更灵活,你可以尝试以下方法:

String stripppedString = myString.replaceAll("(^ )|( $)", "");