Java的split方法說明


相信大家都經常使用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);
    }

經查找API發現在String類中,存在兩個split重載方法

1.public String[] split(String regex)

根據給定正則表達式的匹配拆分此字符串。

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

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

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

 

 
 

參數:
    regex - 定界正則表達式
返回:
字符串數組,它是根據給定正則表達式的匹配拆分此字符串確定的
拋出:
PatternSyntaxException - 如果正則表達式的語法無效

2.public String[] split(String regex,int limit)

根據匹配給定的正則表達式來拆分此字符串。

此方法返回的數組包含此字符串的子字符串,每個子字符串都由另一個匹配給定表達式的子字符串終止,或者由此字符串末尾終止。數組中的子字符串按它們在此字符串中出現的順序排列。如果表達式不匹配輸入的任何部分,那么所得數組只具有一個元素,即此字符串。

limit 參數控制模式應用的次數,因此影響所得數組的長度。如果該限制 n 大於 0,則模式將被最多應用 n - 1 次,數組的長度將不會大於 n,而且數組的最后一項將包含所有超出最后匹配的定界符的輸入。如果 n 為非正,那么模式將被應用盡可能多的次數,而且數組可以是任何長度。如果 n 為 0,那么模式將被應用盡可能多的次數,數組可以是任何長度,並且結尾空字符串將被丟棄。

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

Regex Limit 結果
: 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" } 

 

 

 

 

 

 

 

調用此方法的 str.split(regex, n) 形式與以下表達式產生的結果完全相同:

    Pattern.compile(regex).split(str, n)

參數:
regex - 定界正則表達式
limit - 結果閾值,如上所述
返回:
字符串數組,它是根據給定正則表達式的匹配拆分此字符串確定的
拋出:
PatternSyntaxException - 如果正則表達式的語法無效


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM