且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java中LTRIM和RTRIM的一个很好的替代品是什么?

更新时间:2023-02-06 11:00:42

使用正则表达式可以写:

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("");
}






从绩效角度来看,一个快速的微观基准显示(发布JIT编译),正则表达式方法比循环慢约5倍(0.49s与100万ltrim的0.11s)。


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.