从Java字符串中去掉前导和尾随空格

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

喜欢的东西:

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

结果:

no spaces:keep this

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

437897 次浏览

您可以尝试trim()方法。

String newString = oldString.trim();

看看javadocs

文档:

String.trim();

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

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

使用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"

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

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

这里将剥离开头和结尾空间逗号

S.strip()你可以从Java 11开始使用。

S.trim()你可以使用。

private void capitaliseEveryWordInASentence() {


String mm = "Hello there, this is the cluster";


String[] words = mm.split(" ");
String outt = "";


for (String w : words) {


outt = outt + Character.toUpperCase(w.charAt(0)) + w.substring(1) + " ";
}


System.out.println(outt.trim());
}