Regex-based solutions are particularly slow and perform poorly for this problem. The reason is that they were designed for significantly more complicated and complex problems than this, and you end up using a cannon to kill an ant.
To design the ideal solution in terms of performance, nothing better than looking at the source code of the method String.trim()
, that in Openjdk 8 that’s how it is:
public String trim() {
int len = value.length;
int st = 0;
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[st] <= ' ')) {
st++;
}
while ((st < len) && (val[len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}
Observe the two loops while
. The first loop is skipping the spaces of the beginning, while the second loop is discounting the spaces of the end. It is therefore possible to create a version of rtrim()
and of ltrim()
by doing the following:
- Implement two distant versions of this method above, taking a loop from one of them and the other loop from the other.
- Make the necessary modifications to put these methods in another auxiliary class, since it is not possible to add them directly to the class
String
.
- Simplify the resulting code. Once each of the resulting methods will do the
trim
only on the one hand, it is possible to simplify or remove some expressions that would be constant, or always true or always false that would only be important if the trim
either way.
Here is the resulting code:
public static String rtrim(String toTrim) {
char[] val = toTrim.toCharArray();
int len = val.length;
while (len > 0 && val[len - 1] <= ' ') {
len--;
}
return len < val.length ? toTrim.substring(0, len) : toTrim;
}
public static String ltrim(String toTrim) {
int st = 0;
char[] val = toTrim.toCharArray();
int len = val.length;
while (st < len && val[st] <= ' ') {
st++;
}
return st > 0 ? toTrim.substring(st, len) : toTrim;
}
See here a working test on Ideone.
This guy
Regex
seems to know the answer to everything, awesome.– Paulo Roberto Rosa
Regex
life saver =D– Maicon Carraro
"What a
Regex
and silver tape not solve, nothing else will solve."– Calebe Oliveira