相信大家都常使用String 的split方法,但大家有沒有遇到下面的這種情況:
大家想想下面的程式碼執行結果是什麼
public static void main(String[] args) { // TODO Auto-generated method stub String str1 = "a,b,c,,,a"; String str2 = "a,b,c,,,"; String str3 = "a,b,c, , ,"; String[] s1 = str1.split(","); String[] s2 = str2.split(","); String[] s3 = str3.split(","); System.out.println("str1长度:"+s1.length); System.out.println("str2长度:"+s2.length); System.out.println("str3长度:"+s3.length); }
執行結果:
執行結果:執行結果:執行結果:執行結果:
執行結果:
出現這樣的結果呢,查找API發現了解決方法
解決方法:
透過查看API我們發現我們常用的split方法預設傳遞的是0,現在解決str2輸出空的解決方法是傳遞的第二個參數為負數,即可
public static void main(String[] args) { // TODO Auto-generated method stub String str1 = "a,b,c,,,a"; String str2 = "a,b,c,,,"; String str3 = "a,b,c, , ,"; String[] s1 = str1.split(","); String[] s2 = str2.split(",",-1); String[] s3 = str3.split(",",-1); System.out.println("str1长度:"+s1.length); System.out.println("str2长度:"+s2.length); System.out.println("str3长度:"+s3.length); }
1.public String[] split(String regex)
該方法的作用就像是使用給定的表達式和限制參數 0 來呼叫兩參數 split 方法。因此,所得數組中不包括結尾空字串。
Regex 結果
: { "boo", "and", "foo" } o { "b", "", ":and:f" }
: 2 { "boo", "and:foo" } : 5 { "boo", "and", "foo" } : -2 { "boo", "and", "foo" } o 5 { "b", "", ":and:f", "", "" } o -2 { "b", "", ":and:f", "", "" } o 0 { "b", "", ":and:f" }