本文将通过学习 Spring 的 StringUtils 源码和 JDK 的 String 源码,比较一下两者在实现去除字符串两端空白字符的实现方式和思路。
/**
* Trim leading and trailing whitespace from the given {@code String}.
* @param str the {@code String} to check
* @return the trimmed {@code String}
* @see java.lang.Character#isWhitespace
*/
public static String trimWhitespace(String str) {
if (!hasLength(str)) {
return str;
}
int beginIndex = 0;
int endIndex = str.length() - 1;
while (beginIndex <= endIndex && Character.isWhitespace(str.charAt(beginIndex))) {
beginIndex++;
}
while (endIndex > beginIndex && Character.isWhitespace(str.charAt(endIndex))) {
endIndex--;
}
return str.substring(beginIndex, endIndex + 1);
}java.lang.String 的 trim() 方法源码如下:
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;
}通过上面代码可知,均是通过从左边和右边开始找到第一个不是空白字符串的字符的下标,找到开始位置和结束位置。然后通过字符串切割来实现去除空白字符,笔者以前在部分 JS 代码中看见,有的开发者是使用正则表达式进行去除。如下:
var str = " hello wrold "; str = str.replace(/(^\s+)|(\s+$)/g, ""); console.log(str);
使用正则和使用下标方式效率请读者自行测试。