Java工具类String中trim()方法

String中trim()方法作用

输入参数为null时返回null,否则去除掉字符串两边的空格或者制表符

测试

public class TrimTest {
    public static void main(String[] args) {
        String st1 = "";
        String st2= "hello word ";
        String st3 = " hello word";
        String st4 ="   hello word   ";
        System.out.println("st1:" + st1.trim());
        System.out.println("st2:" + st2.trim());
        System.out.println("st3:" + st3.trim());
        System.out.println("st4:" + st4.trim() +"!!!");
    }
}   

输出结果:

st1:
st2:hello word
st3:hello word
st4:hello word!!!

源码:

可以看到源码中是通过判断字符串前和后面的空格长度,然后进行截取

public String trim() {
            int len = value.length;
            int st = 0;
            char[] val = value;     

            while ((st < len) && (val[st] <= ' ')) {
                st++;
            }
            while ((st < len) && (val[len - 1] <= ' ')) {
                len--;
            }
            return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
        }

如果输入的是空字符串,会报空指针错误

String st1 = null;
System.out.println("st1:" + st1.trim());

报错:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/mengmengdastyle/article/details/81302410