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

291
有没有方便的方法可以从Java字符串中去除任何前导或尾随空格?类似这样的东西:
String myString = "  keep this  ";
String stripppedString = myString.strip();
System.out.println("no spaces:" + strippedString);

结果:

no spaces:keep this

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


7
很遗憾,但这意味着这里的答案对人们很有用。出于这个原因,我点了赞。 - Alex D
12
虽然这可能是一个重复问题,但它表述得更好。如果必要,其他的应该被标记为这个问题的重复。 - thecoshman
1
我更改了重复的内容,因为这个问答有更多的浏览量和收藏,而另一个问答实际上是一个调试问题。 - Radiodef
1
使用JDK/11 API的解决方案 - **String.strip**,回答了这个问题。 - Naman
8个回答

618
你可以尝试使用 trim() 方法。
String newString = oldString.trim();

请查看Java文档


1
作为 Java 11 的 String.strip() 的向后兼容替代品工作。我还没有时间探索微妙的差异。 - Josiah Yoder

86

使用String#trim()方法或String allRemoved = myString.replaceAll("^\\s+|\\s+$", "")来同时去除字符串两端的空格。

针对左侧空格的操作:

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

对于右侧修剪:

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

4
这有个额外的好处,可以告诉你字符串前面/后面有多少空格。 - Błażej Czapp

34

根据文档

String.trim();

18

如果你想使用更灵活的 replace 方法,你可以尝试以下方式:

使用 trim() 是一种选择,但是如果你希望使用 replace 方法,这可能会更加灵活。

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

它会替换哪些内容?空格和换行符可能吗? - Someone Somewhere
我正在寻找一个解决方案,以仅删除字符串末尾的空格而不是开头的空格。我使用了:str.replaceAll("\s*$", "") 谢谢! - lisa p.

4

在Java-11及以上版本中,您可以使用String.strip API返回一个字符串,该字符串的值是此字符串,删除了所有前导和尾随空格。 该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"

请注意,以下是程序相关内容的翻译。仅返回翻译后的文本::根据 https://dev59.com/0m865IYBdhLWcg3wd-ce#PdYjoYgBc1ULPQZFbZpz 的评论,将答案迁移到此处。 - Naman

1

从Java 11开始,您可以使用s.strip()。

您可以使用s.trim()。


1
要删除特定字符,可以使用以下代码:

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

这里将会去除前后的空格逗号


-1
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());
}

目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community
看起来你在回答一个完全不同的问题。 - Federico klez Culloca

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接