猿问

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

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


就像是:


String myString = "  keep this  ";

String stripppedString = myString.strip();

System.out.println("no spaces:" + strippedString);

结果:


no spaces:keep this

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


Qyouu
浏览 925回答 4
4回答

繁花不似锦

您可以尝试trim()方法。String newString = oldString.trim();看看javadocs

qq_花开花谢_0

trim()是您的选择,但是如果您想使用replacemethod -可能更灵活,则可以尝试以下操作:String stripppedString = myString.replaceAll("(^ )|( $)", "");

慕少森

现在,使用java-11,您可以利用String.stripAPI返回一个值为该字符串的字符串,并删除所有前导和尾随空格。相同的javadoc读取:/**&nbsp;* Returns a string whose value is this string, with all leading&nbsp;* and trailing {@link Character#isWhitespace(int) white space}&nbsp;* removed.&nbsp;* <p>&nbsp;* If this {@code String} object represents an empty string,&nbsp;* or if all code points in this string are&nbsp;* {@link Character#isWhitespace(int) white space}, then an empty string&nbsp;* is returned.&nbsp;* <p>&nbsp;* Otherwise, returns a substring of this string beginning with the first&nbsp;* code point that is not a {@link Character#isWhitespace(int) white space}&nbsp;* up to and including the last code point that is not a&nbsp;* {@link Character#isWhitespace(int) white space}.&nbsp;* <p>&nbsp;* This method may be used to strip&nbsp;* {@link Character#isWhitespace(int) white space} from&nbsp;* the beginning and end of a string.&nbsp;*&nbsp;* @return&nbsp; a string whose value is this string, with all leading&nbsp;*&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; and trailing white space removed&nbsp;*&nbsp;* @see Character#isWhitespace(int)&nbsp;*&nbsp;* @since 11&nbsp;*/public String strip()这些示例案例可能是:-System.out.println("&nbsp; leading".strip()); // prints "leading"System.out.println("trailing&nbsp; ".strip()); // prints "trailing"System.out.println("&nbsp; keep this&nbsp; ".strip()); // prints "keep this"
随时随地看视频慕课网APP

相关分类

Java
我要回答