JAVA的split使用注意事項
阿新 • • 發佈:2018-12-31
今天同事遇到的split的有趣情況
測試原始碼如下:
import org.junit.Test;
@Test
public void StringSplit(){
System.out.println("雙引號之間是被split的字元");
System.out.println();
String str1 = "";
String[] strArr1 = str1.split(",");
System.out.println(" 0個逗號: ");
System.out.println (" \""+str1+"\".split(\",\").length="+strArr1.length);
System.out.println();
String str2 = ",,,,";
String[] strArr2 = str2.split(",");
System.out.println(" N(N>0)個純逗號:");
System.out.println("\""+str2+"\".split(\",\").length="+strArr2.length);
System. out.println();
String str3 = ",A,,A,";
String[] strArr3 = str3.split(",");
System.out.println(" 4個純逗號,最後一個字元在最後一個逗號之前,最後逗號後是空字元:");
System.out.println("\""+str3+"\".split(\",\").length="+strArr3.length);
System.out.println();
String str4 = ",,,,A" ;
String[] strArr4 = str4.split(",");
System.out.println(" 4個逗號結尾是字元(本例是A)");
System.out.println(":\""+str4+"\".split(\",\").length="+strArr4.length);
System.out.println();
String str5 =",,A,,A,,";
String[] strArr5 = str5.split(",");
System.out.println(" 6個純逗號,最後一個字元在倒數第二個逗號之前,最後逗號後是空字元");
System.out.println("\""+str5+"\".split(\",\").length="+strArr5.length);
System.out.println();
String str7 =",,,A,,,A, , ,, ";
String[] strArr7 = str7.split(",");
System.out.println(" 10個逗號,最終結尾是空格:");
System.out.println("\""+str7+"\".split(\",\").length="+strArr7.length);
System.out.println();
String str8 =",,,,,,,,,, ";
String[] strArr8 = str8.split(",");
System.out.println(" 10個逗號,最終結尾是空格:");
System.out.println("\""+str8+"\".split(\",\").length="+strArr8.length);
}
輸出結果:
0個逗號:
“”.split(",").length=1
N(N>0)個純逗號:
“,”.split(",").length=0
4個純逗號,最後一個字元在最後一個逗號之前,最後逗號後是空字元:
“,A,A,”.split(",").length=4
4個逗號結尾是字元(本例是A)
:",A".split(",").length=5
6個純逗號,最後一個字元在倒數第二個逗號之前,最後逗號後是空字元
“,A,A,”.split(",").length=5
10個逗號,最終結尾是空格:
“,A,A, , , “.split(”,”).length=11
10個逗號,最終結尾是空格:
“, “.split(”,”).length=11
結論:如果想要獲得逗號+1數量的陣列,最後一個逗號後一定要有字元,空格也可以.