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

前端 未结 10 1408
野的像风
野的像风 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条回答
  •  旧时难觅i
    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
    

提交回复
热议问题