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

yegor256 picture yegor256 · Mar 22, 2013 · Viewed 69.9k times · Source

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

Answer

assylias picture assylias · Mar 22, 2013

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.