What is a good alternative of LTRIM and RTRIM in J

2019-01-08 22:03发布

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

标签: java string trim
5条回答
欢心
2楼-- · 2019-01-08 22:30

With a regex you could write:

String s = ...
String ltrim = s.replaceAll("^\\s+","");
String rtrim = s.replaceAll("\\s+$","");

If you have to do it often, you can create and compile a pattern for better performance:

private final static Pattern LTRIM = Pattern.compile("^\\s+");

public static String ltrim(String s) {
    return LTRIM.matcher(s).replaceAll("");
}

From a performance perspective, a quick micro benchmark shows (post JIT compilation) that the regex approach is about 5 times slower than the loop (0.49s vs. 0.11s for 1 million ltrim).

I personally find the regex approach more readable and less error prone but if performance is an issue you should use the loop solution.

查看更多
劫难
3楼-- · 2019-01-08 22:33

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"
查看更多
爷、活的狠高调
4楼-- · 2019-01-08 22:39
import org.apache.commons.lang3.StringUtils;

private String rTrim(String str) {
    return StringUtils.stripEnd(str, /*stripChars*/" ");
}

private String lTrim(String str) {
    return StringUtils.stripStart(str, /*stripChars*/" ");
}
查看更多
时光不老,我们不散
5楼-- · 2019-01-08 22:47

Based on the answer of @bezmax I had a look at the Spring StringUtils, but it couldn't justify the overload for me of switching to the Spring framework. Therfore I decided to create a Characters class to easily left / right trim strings for any given character(-class). The class is available on GitHub.

Characters.valueOf('x').trim( ... )
Characters.valueOf('x').leftTrim( ... )
Characters.valueOf('x').rightTrim( ... )

If you would like to trim for whitespaces, there is a predefined character-class available:

Characters.WHITESPACE.trim( ... )
Characters.WHITESPACE.leftTrim( ... )
Characters.WHITESPACE.rightTrim( ... )

The class does feature also other kinds of character operations, such condense, replace or split.

查看更多
该账号已被封号
6楼-- · 2019-01-08 22:50

Guava has CharMatcher trimLeadingFrom and trimTrailingFrom

e.g. CharMatcher.whitespace.trimTrailingFrom(s)

查看更多
登录 后发表回答