博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
String.trim
阅读量:4166 次
发布时间:2019-05-26

本文共 1293 字,大约阅读时间需要 4 分钟。

 

trim()方法实际上trim掉了字符串两端Unicode编码小于等于32(\u0020)的所有字符

/**     * @return  A string whose value is this string, with any leading and trailing white     *          space removed, or this string if it has no leading or     *          trailing white space.     */    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;    }

trim()方法实际上的行为并不是”去掉两端的空白字符“,而是”截取中间的非空白字符“

public String substring(int beginIndex, int endIndex) {        if (beginIndex < 0) {            throw new StringIndexOutOfBoundsException(beginIndex);        }        if (endIndex > value.length) {            throw new StringIndexOutOfBoundsException(endIndex);        }        int subLen = endIndex - beginIndex;        if (subLen < 0) {            throw new StringIndexOutOfBoundsException(subLen);        }        return ((beginIndex == 0) && (endIndex == value.length)) ? this                : new String(value, beginIndex, subLen);    }

substring()无法像我们写String str = “abc”这样直接在常量池中创建对象,所以它返回的是一个new出来的对象,这个对象位于Heap内存中

转载地址:http://wwgxi.baihongyu.com/

你可能感兴趣的文章
python zip( )函数
查看>>
python 矩阵转置
查看>>
python 使用zip合并相邻的列表项
查看>>
python iter( )函数
查看>>
python callable()函数
查看>>
python 使用zip反转字典
查看>>
Python内置函数chr() unichr() ord()
查看>>
Python列表解析
查看>>
Python 如何生成矩阵
查看>>
Python 迭代器(iterator)
查看>>
Python enumerate类
查看>>
leetcode 151 Reverse Words in a String (python)
查看>>
leetcode 99 Recover Binary Search Tree (python)
查看>>
Python 生成器(generator)
查看>>
leetcode 98 Validate Binary Search Tree (python)
查看>>
python 三元条件判断的3种实现方法
查看>>
leetcode 97 Interleaving String(python)
查看>>
leetcode 92 Reverse Linked List II
查看>>
leetcode 78 Subsets
查看>>
leetcode 90 Subsets II
查看>>