Spring 和 JDK 是怎样去实现字符串 trim() 方法

本文将通过学习 Spring 的 StringUtils 源码和 JDK 的 String 源码,比较一下两者在实现去除字符串两端空白字符的实现方式和思路。

本文将通过学习 Spring 的 StringUtils 源码和 JDK 的 String 源码,比较一下两者在实现去除字符串两端空白字符的实现方式和思路。

Spring 代码

/**
 * 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);
}

JDK 代码

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);

使用正则和使用下标方式效率请读者自行测试。

一寸光阴一寸金,寸金难买寸光阴。——《增广贤文》
0 不喜欢
说说我的看法 -
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号