Solutions based on regex are particularly slow and have poor performance for this problem. The reason is that they have been 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 String.trim()
method, which in OpenJDK 8 looks like this:
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;
}
Notice the two while
loops. The first loop is jumping the spaces of the beginning, while the second is discounting the spaces of the end. Therefore, it is possible to create a version of rtrim()
and 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 place these methods in another helper class, since it is not possible to add them directly to the
String
class.
- Simplify the resulting code. Since each of the resulting methods will only do% s of one side, 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
was on both sides.
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 test running on Ideone .