String的split小記

public class SplitDemo {
    public static void main(String[] args) {
        String a = "abcooob";
        String[] as = a.split("o");
        System.out.println(as.length);
    }
}

運行結果是

4
abc            b

因爲分割成{“abc”,"","","b"}的值,這個正常理解。

public class SplitDemo {
    public static void main(String[] args) {
        String a = "abcooo";
        String[] as = a.split("o");
        System.out.println(as.length);
        for (String string : as) {
            System.out.print(string+"\t");
        }
    }
}

這個運行結果是:

1
abc   
---------------------------------------------------------

爲什麼呢?

看api

wKiom1dma-qwCGyIAAA1RTx7M2g621.png-wh_50


split

public String[] split(String regex)
  • 根據給定正則表達式的匹配拆分此字符串。

    該方法的作用就像是使用給定的表達式和限制參數 0 來調用兩參數 split 方法。因此,所得數組中不包括結尾空字符串。

    例如,字符串 "boo:and:foo" 使用這些表達式可生成以下結果:

    Regex結果
    :{ "boo", "and", "foo" }
    o{ "b", "", ":and:f" }

    • 參數:

    • regex - 定界正則表達式

    • 返回:

    • 字符串數組,它是根據給定正則表達式的匹配拆分此字符串確定的

    • 拋出:

    • PatternSyntaxException - 如果正則表達式的語法無效



----------------------------------------------------------------------------------

結論:split分割所得數組中不包括結尾空字符串。

----------------------------------------------------------------------------------

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