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

報錯:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章