Re: How to trim a String trailing spaces, but not leading spaces?
Recently, www <www@nospam.com> wrote:
[...]
String method replaceAll("\\s+$", ""):
[...]
I also learned a tip about regular expression.
As did I. Sadly, they tend to be slow. Curious, I compared the regex to
Lew's loop proposal. The latter is an order of magnitude faster. The two
also elide different characters, although I only tested the ones in
common:
<http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html>
<http://java.sun.com/javase/6/docs/api/java/lang/Character.html#isWhitesp
ace(int)>
<sscce>
public class RightTrim {
private static final String TEST = "Test \t\n\u000B\f\r";
public static void main(String[] args) {
(new RegEx()).test(TEST);
(new Loop()).test(TEST);
}
}
abstract class Test {
public static final int COUNT = 100000;
public void test(String in) {
long start = System.currentTimeMillis();
for (int i = 0; i < COUNT; i++) rTrim(in);
System.out.println(System.currentTimeMillis() - start);
}
public abstract String rTrim(String in);
}
/** @author JBM */
class RegEx extends Test {
public String rTrim( String in ) {
return in.replaceAll("\\s+$", "");
}
}
/** @author Lew */
class Loop extends Test {
public String rTrim( String in ) {
int len = in.length();
while ( len > 0 ) {
if ( ! Character.isWhitespace( in.charAt( --len ))) {
return in.substring( 0, len + 1 );
}
}
return "";
}
}
</sscce>
Thank you very much.
My pleasure.
--
John B. Matthews
trashgod at gmail dot com
home dot woh dot rr dot com slash jbmatthews