问题描述
Java的一个很好的替代方法 ltrim()
和 rtrim()
函数是什么?
What is a good alternative of JavaScript ltrim()
and rtrim()
functions in Java?
推荐答案
使用正则表达式可以写:
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.
这篇关于Java中LTRIM和RTRIM的一个很好的替代品是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!