ChatGPT解决这个技术问题 Extra ChatGPT

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

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

就像是:

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

结果:

no spaces:keep this

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

这很不幸,但这意味着这里的答案对人们有用。我仅出于这个原因投票。
虽然这可能是重复的,但这是迄今为止提出的更好的问题。如果有的话,另一个应该作为这个的副本关闭。
我切换了重复,因为这个问答有更多的观点和收藏,而另一个问答实际上是一个调试问题。
使用 solution from JDK/11 API - String.strip 对此进行了回答。

s
szedjani

你可以试试 trim() 方法。

String newString = oldString.trim();

看看javadocs


作为 Java 11 的 String.strip() 的向后兼容替代品。我还没有时间探索细微的差异。
F
Frank Essenberger

使用 String#trim() 方法或 String allRemoved = myString.replaceAll("^\\s+|\\s+$", "") 修剪两端。

对于左装饰:

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

对于右修剪:

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

这有一个额外的好处,就是能够知道字符串中有多少前导/尾随空格。
R
Richard H

docs

String.trim();

J
James.Xu

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

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

它取代了什么?空格和换行符可能吗?
我正在寻找一种解决方案,只删除尾随空格而不是前导空格。我用过:str.replaceAll("\\s*$", "") 谢谢!
N
Naman

对于 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"

G
Galley

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

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

这里将去掉前导和尾随空格和逗号。


S
Satya

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

s.trim() 你可以使用。


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

正如目前所写的那样,您的答案尚不清楚。请edit添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。您可以找到有关如何写出好答案的更多信息in the help center
看起来你在这里回答了一个完全不同的问题。