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

前端 未结 10 1392
野的像风
野的像风 2020-11-30 01:37

The trim() function removes both the trailing and leading space, however, if I only want to remove the trailing space of a string, how can I do it?

相关标签:
10条回答
  • 2020-11-30 02:25

    String value= "Welcome to java ";

    So we can use

    value = value.trim();

    0 讨论(0)
  • 2020-11-30 02:27

    I modified the original java.lang.String.trim() method a bit and it should work:

      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
    
    0 讨论(0)
  • 2020-11-30 02:29

    Since JDK 11

    If you are on JDK 11 or higher you should probably be using stripTrailing().


    Earlier JDK versions

    Using the regular expression \s++$, you can replace all trailing space characters (includes space and tab characters) with the empty string ("").

    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,
    • ++ – match one or more of the previous token (possessively); i.e., 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

    • Java regular expression syntax
    0 讨论(0)
  • 2020-11-30 02:33

    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.

    0 讨论(0)
提交回复
热议问题