是否有一种方便的方法可以从 Java 字符串中去除任何前导或尾随空格?
就像是:
String myString = " keep this ";
String stripppedString = myString.strip();
System.out.println("no spaces:" + strippedString);
结果:
no spaces:keep this
myString.replace(" ","")
将替换 keep 和 this 之间的空格。
String.strip
对此进行了回答。
你可以试试 trim() 方法。
String newString = oldString.trim();
看看javadocs
使用 String#trim()
方法或 String allRemoved = myString.replaceAll("^\\s+|\\s+$", "")
修剪两端。
对于左装饰:
String leftRemoved = myString.replaceAll("^\\s+", "");
对于右修剪:
String rightRemoved = myString.replaceAll("\\s+$", "");
trim() 是您的选择,但如果您想使用 replace
方法——这可能更灵活,您可以尝试以下方法:
String stripppedString = myString.replaceAll("(^ )|( $)", "");
对于 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());
}