相信大家都經常使用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.}執行結果:
為什么會出現這樣的結果呢,查找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(Stringregex)
根據給定正則表達式的匹配拆分此字符串。
該方法的作用就像是使用給定的表達式和限制參數 0 來調用兩參數
split
方法。因此,所得數組中不包括結尾空字符串。例如,字符串"boo:and:foo"使用這些表達式可生成以下結果:
Regex | 結果 |
---|---|
: | { "boo", "and", "foo" } |
o | { "b", "", ":and:f" } |
參數:
regex
- 定界正則表達式PatternSyntaxException
- 如果正則表達式的語法無效2.public String[] split(Stringregex,intlimit)
根據匹配給定的正則表達式來拆分此字符串。
此方法返回的數組包含此字符串的子字符串,每個子字符串都由另一個匹配給定表達式的子字符串終止,或者由此字符串末尾終止。數組中的子字符串按它們在此字符串中出現的順序排列。如果表達式不匹配輸入的任何部分,那么所得數組只具有一個元素,即此字符串。
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
- 如果正則表達式的語法無效新聞熱點
疑難解答