java中split()的用法

 

今天寫個程序用到java裏面的split()函數時,發現能夠有兩個參數,以前用這個函數一直是用的一個參數,今天試了下兩個參數的使用,記錄一下區別。java

 

下面是菜鳥裏關於split()函數的定義數組

 

經過這個定義能夠發現,第一個參數是split()函數對字符串分割的根據,第二個參數是分割的份數。函數

 

第二個參數有兩種寫法spa

  • 一種是比較直觀的,直接輸入要分割的份數a
  • 另外一種是-1,輸入-1能夠理解爲無限制匹配,也就是即便兩個符號之間沒有內容,也會在數組裏面存一個空的值。第二個參數輸入-1和不輸入第二個參數的效果是同樣的。

 

具體的內容看下面的代碼比較清晰3d

package _2_2_test;blog

 

public class one {字符串

 

public static void main(String[] args) {it

// TODO Auto-generated method stubclass

String str = "192.168.1.1.........3.4";test

 

String result1[] = str.split("\\.");

for (String s : result1) {

System.out.println(s);

}

 

System.out.println("-------------");

 

String result2[] = str.split("\\.", 5);

for (String s : result2) {

System.out.println(s);

}

 

System.out.println("-------------");

 

String result3[] = str.split("\\.", -1);

for (String s : result3) {

System.out.println(s);

}

 

System.out.println("result1的分割份數:" + result1.length);

System.out.println("result2的分割份數:" + result2.length);

System.out.println("result3的分割份數:" + result3.length);

}

 

}

  

最後的結果也比較直觀

相關文章
相關標籤/搜索