java split(String regex, int limit) 的使用


項目中遇到了這樣一個問題,對 String str = ",," 調用 split(",")方法,預期結果是返回一個長度為 3 的String數組,且每一個元素都為空字符串 ""。但實際結果返還的是一個空數組,長度為 0 。

百度之,原來java中還有 split(String regex, int limit)這中用法,String[] java.lang.String.split(String regex, int limit),其中regex為分割正則表達式,limit為分割次數限制,官方文檔這樣解釋:

 

1. The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

當 limit  > 0的時候,str將被分割 limit - 1次:

1 String str = ",,,,";
2 String [] strLst = str.split(",", 2);                
3 System.out.println(strLst.length);
4 
5 for (String e : strLst) {
6      System.out.println(e);
7 }

輸出為:

2

,,,

2. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. 

當 limit < 0 的時候,str將被盡可能多的分割:

1    
2 String str = ",,,,";
3 String [] strLst = str.split(",", -1);                
4 System.out.println(strLst.length);
5 
6 for (String e : strLst) {
7      System.out.println(e);
8 }

輸出為:

5

3.  If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded

當 limt = 0 的時候,str被盡可能多的分割,但是尾部的空字符串會被拋棄:

 1         String str = ",,,,";
 2         String [] strLst = str.split(",", 0);                
 3         System.out.println(strLst.length);
 4         for (String e : strLst) {
 5             System.out.println(e);
 6         }
 7         
 8         str = "a,b,,,";
 9         strLst = str.split(",", 0);
10         System.out.println(strLst.length);
11         for (String e : strLst) {
12             System.out.println(e);
13         }

輸出為:

0
2
a
b

 

對於 沒有 limit 參數的 split函數, 官方解釋如下:

String[] java. lang. String.split( String regex)

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array. 

也就是等價於 limt = 0 的情況,尾部的空字符串被舍棄掉:

1         String str = "a,b,,,";
2         String [] strLst = str.split(",");                
3         System.out.println(strLst.length);
4         for (String e : strLst) {
5             System.out.println(e);
6         }

輸出為:

2
a
b

 


免責聲明!

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



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