What is a good alternative of LTRIM and RTRIM in Java?

后端 未结 7 905
既然无缘
既然无缘 2020-12-01 09:16

What is a good alternative of JavaScript ltrim() and rtrim() functions in Java?

7条回答
  •  长情又很酷
    2020-12-01 09:38

    Using regex may be nice, but it's quite a lot slower than a simple trimming functions:

    public static String ltrim(String s) {
        int i = 0;
        while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
            i++;
        }
        return s.substring(i);
    }
    
    public static String rtrim(String s) {
        int i = s.length()-1;
        while (i >= 0 && Character.isWhitespace(s.charAt(i))) {
            i--;
        }
        return s.substring(0,i+1);
    }
    

    Source: http://www.fromdev.com/2009/07/playing-with-java-string-trim-basics.html

    Also, there are some libraries providing such functions. For example, Spring StringUtils. Apache Commons StringUtils provides similar functions too: strip, stripStart, stripEnd

    StringUtils.stripEnd("abc  ", null)    = "abc"
    

提交回复
热议问题