-
Enhancement
-
Resolution: Fixed
-
P4
-
15
-
b02
Utils has the following couple of methods: removeLeadingWhitespace and removeTrailingWhitespace. Both unconditionally call toCharArray, which will return a *copy* of the underlying character content.
At a minimum, it may be better to do a one-off check of the first or last character, so see if the character array is actually needed; it may also be desirable just to iterate over the string characters instead of over a copy of the characters. Presumably the amount of leading or trailing whitespace is typically small compared to the rest of the content.
private String removeTrailingWhitespace(String text) {
char[] buf = text.toCharArray();
for (int i = buf.length - 1; i > 0 ; i--) {
if (!Character.isWhitespace(buf[i]))
return text.substring(0, i + 1);
}
return text;
}
private String removeLeadingWhitespace(String text) {
char[] buf = text.toCharArray();
for (int i = 0; i < buf.length; i++) {
if (!Character.isWhitespace(buf[i])) {
return text.substring(i);
}
}
return text;
}
At a minimum, it may be better to do a one-off check of the first or last character, so see if the character array is actually needed; it may also be desirable just to iterate over the string characters instead of over a copy of the characters. Presumably the amount of leading or trailing whitespace is typically small compared to the rest of the content.
private String removeTrailingWhitespace(String text) {
char[] buf = text.toCharArray();
for (int i = buf.length - 1; i > 0 ; i--) {
if (!Character.isWhitespace(buf[i]))
return text.substring(0, i + 1);
}
return text;
}
private String removeLeadingWhitespace(String text) {
char[] buf = text.toCharArray();
for (int i = 0; i < buf.length; i++) {
if (!Character.isWhitespace(buf[i])) {
return text.substring(i);
}
}
return text;
}