String的trim()和substring()

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

如果两端有空格,则调用substring()将空格截掉,如果没空格则返回原对象

substring()
	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);
    }

当输入的起始索引与同字符串的起始索引一致时,返回原字符串,而如果不一致且不抛异常的情况下,则将起始索引部分从字符串中截取下来,这里是新new了一个String对象

举例:

		String str = "ab";
        String str1 = (" a"+"b ").trim();
        String str2 = ("a"+"b").trim();
        System.out.println(str==str1);
        System.out.println(str==str2);

str1因为两边有空格,所以调用trim()方法时,内部的substring()方法会将截取的部分new成一个String对象,所以str==str1为false,因为一个指向常量池中的值,一个指向堆中的对象,地址不同;

而str2因为两边并没有空格,所以trim()方法直接返回原对象,所以str==str2为true,因为两个都是指向常量池中的值,且常量池中的值是唯一的,所以str和str2都指向常量池中ab的值,地址相同。

【参考文档】
String.trim()源码解析

猜你喜欢

转载自blog.csdn.net/qq_36281031/article/details/108455184