简体   繁体   English

如何在Java中只删除字符串的尾随空格并保留前导空格?

[英]How to remove only trailing spaces of a string in Java and keep leading spaces?

trim()函数删除了尾部和前导空格,但是,如果我只想删除字符串的尾随空格,我该怎么办?

Since JDK 11 自JDK 11起

If you are on JDK 11 or higher you should probably be using stripTrailing() . 如果您使用的是JDK 11或更高版本,则应该使用stripTrailing()


Earlier JDK versions 早期的JDK版本

Using the regular expression \\s++$ , you can replace all trailing space characters (includes space and tab characters) with the empty string ( "" ). 使用正则表达式\\s++$ ,可以用空字符串( "" )替换所有尾随空格字符(包括空格和制表符)。

final String text = "  foo   ";
System.out.println(text.replaceFirst("\\s++$", ""));

Output 产量

  foo

Online demo. 在线演示。

Here's a breakdown of the regex: 这是正则表达式的细分:

  • \\s – any whitespace character, \\s - 任何空格字符,
  • ++ – match one or more of the previous token (possessively); ++ - 匹配前一个标记中的一个或多个(占有); ie, match one or more whitespace character. 即,匹配一个或多个空白字符。 The + pattern is used in its possessive form ++ , which takes less time to detect the case when the pattern does not match. +模式以其所有格形式 ++ ,当模式不匹配时,花费较少的时间来检测案例。
  • $ – the end of the string. $ - 字符串的结尾。

Thus, the regular expression will match as much whitespace as it can that is followed directly by the end of the string: in other words, the trailing whitespace. 因此,正则表达式将匹配尽可能多的空格,直接跟随字符串的结尾:换句话说,尾随空格。

The investment into learning regular expressions will become more valuable, if you need to extend your requirements later on. 如果您需要在以后扩展您的要求,那么对学习正则表达式的投入将变得更有价值。

References 参考

另一种选择是使用Apache Commons StringUtils ,特别是StringUtils.stripEnd

String stripped = StringUtils.stripEnd("   my lousy string    "," ");

I modified the original java.lang.String.trim() method a bit and it should work: 我稍微修改了原始java.lang.String.trim()方法,它应该工作:

  public String trim(String str) {
        int len = str.length();
        int st = 0;

        char[] val = str.toCharArray();

        while ((st < len) && (val[len - 1] <= ' ')) {
            len--;
        }
        return str.substring(st, len);
    }

Test: 测试:

  Test test = new Test();
  String sample = "            Hello World               "; // A String with trailing and leading spaces
  System.out.println(test.trim(sample) + " // No trailing spaces left");

Output: 输出:

        Hello World // No trailing spaces left

The most practical answer is @Micha's, Ahmad's is reverse of what you wanted so but here's what I came up with in case you'd prefer not to use unfamiliar tools or to see a concrete approach. 最实际的答案是@Micha, Ahmad与你想要的相反, 但这就是我想出的,以防你不想使用不熟悉的工具或看到具体的方法。

public String trimEnd( String myString ) {

    for ( int i = myString.length() - 1; i >= 0; --i ) {
        if ( myString.charAt(i) == ' ' ) {
            continue;
        } else {
            myString = myString.substring( 0, ( i + 1 ) );
            break;
        }
    }
    return myString;
}

Used like: 使用如下:

public static void main( String[] args ) {

    String s = "    Some text here   ";
    System.out.println( s + "|" );
    s = trimEnd( s );
    System.out.println( s + "|" );
}

Output: 输出:

 Some text here | Some text here| 

The best way in my opinion: 我认为最好的方法是:

public static String trimEnd(String source) {
    int pos = source.length() - 1;
    while ((pos >= 0) && Character.isWhitespace(source.charAt(pos))) {
        pos--;
    }
    pos++;
    return (pos < source.length()) ? source.substring(0, pos) : source;
}

This does not allocate any temporary object to do the job and is faster than using a regular expression. 这不会分配任何临时对象来完成工作,并且比使用正则表达式更快。 Also it removes all whitespaces, not just ' '. 它还删除了所有空格,而不仅仅是''。

Here's a very short, efficient and easy-to-read version: 这是一个非常简短,高效且易于阅读的版本:

public static String trimTrailing(String str) {
    if (str != null) {
        for (int i = str.length() - 1; i >= 0; --i) {
            if (str.charAt(i) != ' ') {
                return str.substring(0, i + 1);
            }
        }
    }
    return str;
}

As an alternative to str.charAt(i) != ' ' you can also use !Character.isWhitespace(str.charAt(i) if you want to use a broader definition of whitespace. 作为str.charAt(i) != ' '的替代,你也可以使用!Character.isWhitespace(str.charAt(i)如果你想使用更广泛的空格定义。

JDK11您可以使用stripTrailing

String result = str.stripTrailing();

Spring framework gives a useful org.springframework.util.StringUtils. Spring框架提供了一个有用的org.springframework.util.StringUtils。

trimTrailingWhitespace trimTrailingWhitespace

This code is intended to be read a easily as possible by using descriptive names (and avoiding regular expressions). 此代码旨在通过使用描述性名称(并避免使用正则表达式)尽可能轻松地阅读。

It does use Java 8's Optional so is not appropriate for everyone. 它确实使用Java 8的Optional因此并不适合所有人。

public static String removeTrailingWhitspace(String string) {
    while (hasWhitespaceLastCharacter(string)) {
        string = removeLastCharacter(string);
    }
    return string;
}

private static boolean hasWhitespaceLastCharacter(String string) {
    return getLastCharacter(string)
            .map(Character::isWhitespace)
            .orElse(false);
}

private static Optional<Character> getLastCharacter(String string) {
    if (string.isEmpty()) {
        return Optional.empty();
    }
    return Optional.of(string.charAt(string.length() - 1));
}

private static String removeLastCharacter(String string) {
    if (string.isEmpty()) {
        throw new IllegalArgumentException("String must not be empty");
    }
    return string.substring(0, string.length() - 1);
}

String value= "Welcome to java "; String value =“欢迎使用java”;

So we can use 所以我们可以使用

value = value.trim(); value = value.trim();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM