Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
722 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...