- public String[] split(String regex, int limit)
split函數是用於使用特定的切割符(regex)來分隔字符串成一個字符串數組,這里我就不討論第二個參數(可選)的含義詳見官方API說明
我在做項目期間曾經遇到一個“bug”,就是當split函數處理空字符串時,返回數組的數組竟然有值。。。查完API才發現就是這么規定的。
官方API 寫道
If the expression does not match any part of the input then the resulting array has just one element, namely this string.
原來我不能小看空字符串,它也是字符串的一種,當split函數沒有發現匹配的分隔符時,返回數組就只包含一個元素(該字符串本身)。以為這樣就結束了,幸虧我做了幾個試驗,忽然又發現了一些問題,代碼如下:
- public class Split {
- public static void main(String[] args) {
- String str1 = "a-b";
- String str2 = "a-b-";
- String str3 = "-a-b";
- String str4 = "-a-b-";
- String str5 = "a";
- String str6 = "-";
- String str7 = "--";
- String str8 = ""; //等同於new String()
- getSplitLen(str1);
- getSplitLen(str2);
- getSplitLen(str3);
- getSplitLen(str4);
- getSplitLen(str5);
- getSplitLen(str6);
- getSplitLen(str7);
- getSplitLen(str8);
- }
- public static void getSplitLen(String demo){
- String[] array = demo.split("-");
- int len = array.length;
- System.out.print("\"" + demo + "\"長度為:" + len);
- if(len >= 0){
- for(int i=0; i<len; i++){
- System.out.print(" \""+array[i]+"\"");
- }
- }
- System.out.println();
- }
- }
運行結果:
"a-b"長度為:2 "a" "b"
"a-b-"長度為:2 "a" "b"
"-a-b"長度為:3 "" "a" "b"
"-a-b-"長度為:3 "" "a" "b"
"a"長度為:1 "a"
"-"長度為:0
"--"長度為:0
""長度為:1 ""
和我想的還是不大一樣,因為不知道源碼也不知道具體是怎么實現的,我的理解如下:
- 當字符串只包含分隔符時,返回數組沒有元素;
- 當字符串不包含分隔符時,返回數組只包含一個元素(該字符串本身);
- 字符串最尾部出現的分隔符可以看成不存在,不影響字符串的分隔;
- 字符串最前端出現的分隔符將分隔出一個空字符串以及剩下的部分的正常分隔;