java中split()的用法


 

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

 

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

 

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

 

第二個參數有兩種寫法

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

 

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

package _2_2_test;

 

public class one {

 

public static void main(String[] args) {

// TODO Auto-generated method stub

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

 

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);

}

 

}

  

最后的結果也比較直觀

 


免責聲明!

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



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