close

前幾天為了處理資料時將使用了split來將字串分類

然後程式跳出了 ArrayIndexOutOfBoundsException

看了一下字串明明分格的符號數就正確,一查發現Java的split

造成後面沒有字元時字串分割後會不存入陣列

看以下範例:

public class SplitTest {

    public static void main(String[] args) {
        String str = "1/2/3/4/5////";
        String[] splitStr = str.split("/");
        
        System.out.println("reulst");
        for(int i = 0 ; i < splitStr.length ; i++){
            System.out.println("第" + i + "項:" + splitStr[i]);
        }
    }

}
 

 

當字串用"/"分格時,因為5以後的的字串沒有字元,連空白都沒有

對str做split時他會自動不分類

產出的結果為:

reulst
第0項:1
第1項:2
第2項:3
第3項:4
第4項:5

 

當你把str的字串改為

public class SplitTest {

    public static void main(String[] args) {
        String str = "1/2/3/4/5// ////";
        String[] splitStr = str.split("/",3);
        
        System.out.println("reulst");
        for(int i = 0 ; i < splitStr.length ; i++){
            System.out.println("第" + i + "項:" + splitStr[i]);
        }
    }

}
 

尤於你中間有一項多了一個空白,split會視為有輸入,就會分割

結果如下:

reulst
第0項:1
第1項:2
第2項:3
第3項:4
第4項:5
第5項:
第6項: 

 

另外你可以控制你分割數的上限

比如說

public class SplitTest {

    public static void main(String[] args) {
        String str = "1/2/3/4/5//////";
        String[] splitStr = str.split("/",3);
        
        System.out.println("reulst");
        for(int i = 0 ; i < splitStr.length ; i++){
            System.out.println("第" + i + "項:" + splitStr[i]);
        }
    }

}
 

會產出以下結果:

reulst
第0項:1
第1項:2
第2項:3/4/5//////

 

最後,如果你要將/ 的每一項都分割,split的第二個參數你要帶一個小於0的負數,比如說-1

public class SplitTest {

    public static void main(String[] args) {
        String str = "1/2/3/4/5//////";

        String[] splitStr = str.split("/",-1);
        
        System.out.println("reulst");
        for(int i = 0 ; i < splitStr.length ; i++){
            System.out.println("第" + i + "項:" + splitStr[i]);
        }
    }

}
 


最後的程式結果就會把空白分割出來:

reulst
第0項:1
第1項:2
第2項:3
第3項:4
第4項:5
第5項:
第6項:
第7項:
第8項:
第9項:
第10項:

 

整理一下

1.第二個參數代入負數會將字串完整分割

2.不傳第二個參數,或是第二個參數傳入0,陣列會顯示到最後一個有字元的部份

3.第二個參數傳正數,那最多就把字串分割成傳入的數字

 

arrow
arrow
    文章標籤
    Java
    全站熱搜

    Dnight 發表在 痞客邦 留言(0) 人氣()