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

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...