如何从Java中的字符串中删除前导和尾随空格?

发布于 2025-01-01 21:28:17 字数 169 浏览 2 评论 0原文

我想从字符串中删除前导和尾随空格:

String s = "          Hello World                    ";

我希望结果如下:

s == "Hello world";

I want to remove the leading and trailing whitespace from string:

String s = "          Hello World                    ";

I want the result to be like:

s == "Hello world";

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

短暂陪伴 2025-01-08 21:28:17
 s.trim()

请参阅 String#trim( )

没有任何内部方法,使用正则表达式,如

 s.replaceAll("^\\s+", "").replaceAll("\\s+$", "")

or

  s.replaceAll("^\\s+|\\s+$", "")

或仅使用纯形式的模式

    String s="          Hello World                    ";
    Pattern trimmer = Pattern.compile("^\\s+|\\s+$");
    Matcher m = trimmer.matcher(s);
    StringBuffer out = new StringBuffer();
    while(m.find())
        m.appendReplacement(out, "");
    m.appendTail(out);
    System.out.println(out+"!");
 s.trim()

see String#trim()

Without any internal method, use regex like

 s.replaceAll("^\\s+", "").replaceAll("\\s+$", "")

or

  s.replaceAll("^\\s+|\\s+$", "")

or just use pattern in pure form

    String s="          Hello World                    ";
    Pattern trimmer = Pattern.compile("^\\s+|\\s+$");
    Matcher m = trimmer.matcher(s);
    StringBuffer out = new StringBuffer();
    while(m.find())
        m.appendReplacement(out, "");
    m.appendTail(out);
    System.out.println(out+"!");
烟若柳尘 2025-01-08 21:28:17
String s="Test "; 
s= s.trim();
String s="Test "; 
s= s.trim();
庆幸我还是我 2025-01-08 21:28:17

我不喜欢使用正则表达式来解决琐碎的问题。这将是一个简单的选择:

public static String trim(final String s) {
    final StringBuilder sb = new StringBuilder(s);
    while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0)))
        sb.deleteCharAt(0); // delete from the beginning
    while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1)))
        sb.deleteCharAt(sb.length() - 1); // delete from the end
    return sb.toString();
}

I prefer not to use regular expressions for trivial problems. This would be a simple option:

public static String trim(final String s) {
    final StringBuilder sb = new StringBuilder(s);
    while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0)))
        sb.deleteCharAt(0); // delete from the beginning
    while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1)))
        sb.deleteCharAt(sb.length() - 1); // delete from the end
    return sb.toString();
}
荆棘i 2025-01-08 21:28:17

String.trim() 回答了问题,但对我来说不是一个选择。
此处所述:

它只是将 U+0020(通常的空格字符)之前的任何内容视为空白,将其之上的任何内容视为非空白。

这会导致它修剪 U+0020 空格字符和 U+0020 下面的所有“控制代码”字符(包括 U+0009 制表符),但不会修剪上面的控制代码或 Unicode 空格字符。< /p>

我正在使用日语,我们有全角字符,就像这样,全角空格不会被 String.trim() 修剪。

因此,我创建了一个函数,就像 xehpuk 的代码片段一样,使用 Character.isWhitespace()。
然而,这个版本没有使用 StringBuilder,并且不是删除字符,而是找到从原始字符串中取出修剪子字符串所需的 2 个索引。

public static String trimWhitespace(final String stringToTrim) {
    int endIndex = stringToTrim.length();
    // Return the string if it's empty
    if (endIndex == 0) return stringToTrim;
    int firstIndex = -1;

    // Find first character which is not a whitespace, if any
    // (increment from beginning until either first non whitespace character or end of string)
    while (++firstIndex < endIndex && Character.isWhitespace(stringToTrim.charAt(firstIndex))) { }

    // If firstIndex did not reach end of string, Find last character which is not a whitespace,
    // (decrement from end until last non whitespace character)
    while (--endIndex > firstIndex && Character.isWhitespace(stringToTrim.charAt(endIndex))) { }

    // Return substring using indexes
    return stringToTrim.substring(firstIndex, endIndex + 1);
}

String.trim() answers the question but was not an option for me.
As stated here :

it simply regards anything up to and including U+0020 (the usual space character) as whitespace, and anything above that as non-whitespace.

This results in it trimming the U+0020 space character and all “control code” characters below U+0020 (including the U+0009 tab character), but not the control codes or Unicode space characters that are above that.

I am working with Japanese where we have full-width characters Like this, the full-width space would not be trimmed by String.trim().

I therefore made a function which, like xehpuk's snippet, use Character.isWhitespace().
However, this version is not using a StringBuilder and instead of deleting characters, finds the 2 indexes it needs to take a trimmed substring out of the original String.

public static String trimWhitespace(final String stringToTrim) {
    int endIndex = stringToTrim.length();
    // Return the string if it's empty
    if (endIndex == 0) return stringToTrim;
    int firstIndex = -1;

    // Find first character which is not a whitespace, if any
    // (increment from beginning until either first non whitespace character or end of string)
    while (++firstIndex < endIndex && Character.isWhitespace(stringToTrim.charAt(firstIndex))) { }

    // If firstIndex did not reach end of string, Find last character which is not a whitespace,
    // (decrement from end until last non whitespace character)
    while (--endIndex > firstIndex && Character.isWhitespace(stringToTrim.charAt(endIndex))) { }

    // Return substring using indexes
    return stringToTrim.substring(firstIndex, endIndex + 1);
}
ζ澈沫 2025-01-08 21:28:17

从 Java 11 String 类开始,有 strip() 方法,用于返回值为该字符串的字符串,并删除所有前导和尾随空格。引入这是为了克服修剪方法的问题。

文档: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#strip()

示例:

String str = "  abc    ";
// public String strip()
str = str.strip(); // Returns abc

还有两个比较有用Java 11+ 字符串中的方法类:

  1. stripLeading() :返回一个字符串,其值为该字符串,
    删除所有前导空白。

  2. stripTrailing() :返回一个字符串,其值为该字符串,
    删除所有尾随空格。

Since Java 11 String class has strip() method which is used to returns a string whose value is this string, with all leading and trailing white space removed. This is introduced to overcome the problem of trim method.

Docs: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#strip()

Example:

String str = "  abc    ";
// public String strip()
str = str.strip(); // Returns abc

There are two more useful methods in Java 11+ String class:

  1. stripLeading() : Returns a string whose value is this string,
    with all leading white space removed.

  2. stripTrailing() : Returns a string whose value is this string,
    with all trailing white space removed.

清风疏影 2025-01-08 21:28:17

使用 String 类的修剪方法。它将删除所有前导和尾随空格。

http://docs.oracle.com/javase /1.5.0/docs/api/java/lang/String.html

Use the String class trim method. It will remove all leading and trailing whitespace.

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html

泪眸﹌ 2025-01-08 21:28:17
String s="          Hello World                    ";
s = s.trim();

有关详细信息 请参阅此

String s="          Hello World                    ";
s = s.trim();

For more information See This

戏蝶舞 2025-01-08 21:28:17

只需使用trim()。它仅消除字符串开头和结尾多余的空格。

String fav = "我喜欢苹果";

fav = fav.trim();

System.out.println(fav);

输出:
我喜欢苹果//字符串开头和结尾没有多余的空格

Simply use trim(). It only eliminate the start and end excess white spaces of a string.

String fav = " I like apple ";

fav = fav.trim();

System.out.println(fav);

Output:
I like apple //no extra space at start and end of the string

緦唸λ蓇 2025-01-08 21:28:17
s = s.trim();

更多信息:
http://docs.oracle .com/javase/7/docs/api/java/lang/String.html#trim()

为什么不想使用预定义的方法?他们通常是最有效率的。

s = s.trim();

More info:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#trim()

Why do you not want to use predefined methods? They are usually most efficient.

无名指的心愿 2025-01-08 21:28:17

虽然如果您想避免使用正则表达式,@xehpuk 的方法很好,但它的时间复杂度为 O(n^2)。以下解决方案也避免了正则表达式,但时间复杂度为 O(n):

if(s.length() == 0)
    return "";
char left = s.charAt(0);
char right = s.charAt(s.length() - 1);
int leftWhitespace = 0;
int rightWhitespace = 0;
boolean leftBeforeRight = leftWhitespace < s.length() - 1 - rightWhitespace;

while ((left == ' ' || right == ' ') && leftBeforeRight) {
    if(left == ' ') {
        leftWhitespace++;
        left = s.charAt(leftWhitespace);
    }
    if(right == ' ') {
        rightWhitespace++;
        right = s.charAt(s.length() - 1 - rightWhitespace);
    }

    leftBeforeRight = leftWhitespace < s.length() - 1 - rightWhitespace;
}

String result = s.substring(leftWhitespace, s.length() - rightWhitespace);
return result.equals(" ") ? "" : result;

这对字符串开头和结尾处的尾随空格数进行计数,直到从空格计数获得的“左”和“右”索引满足,或者两个索引满足已达到非空白字符。之后,我们要么返回使用空格计数获得的子字符串,如果结果是空格,则返回空字符串(需要考虑具有奇数个字符的全空格字符串)。

While @xehpuk's method is good if you want to avoid using regex, but it has O(n^2) time complexity. The following solution also avoids regex, but is O(n):

if(s.length() == 0)
    return "";
char left = s.charAt(0);
char right = s.charAt(s.length() - 1);
int leftWhitespace = 0;
int rightWhitespace = 0;
boolean leftBeforeRight = leftWhitespace < s.length() - 1 - rightWhitespace;

while ((left == ' ' || right == ' ') && leftBeforeRight) {
    if(left == ' ') {
        leftWhitespace++;
        left = s.charAt(leftWhitespace);
    }
    if(right == ' ') {
        rightWhitespace++;
        right = s.charAt(s.length() - 1 - rightWhitespace);
    }

    leftBeforeRight = leftWhitespace < s.length() - 1 - rightWhitespace;
}

String result = s.substring(leftWhitespace, s.length() - rightWhitespace);
return result.equals(" ") ? "" : result;

This counts the number of trailing whitespaces in the beginning and end of the string, until either the "left" and "right" indices obtained from whitespace counts meet, or both indices have reached a non-whitespace character. Afterwards, we either return the substring obtained using the whitespace counts, or the empty string if the result is a whitespace (needed to account for all-whitespace strings with odd number of characters).

月下凄凉 2025-01-08 21:28:17

没有 trim 方法就很简单:

String s = "          Hello World                    ";
System.out.println(s.substring(10, 21));

It's simple without trim method:

String s = "          Hello World                    ";
System.out.println(s.substring(10, 21));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文