?split函數(shù)
```
String a = "a,a,a,a"; System.out.println(a.split(",").length); //結果為4 String a = "a,,,4"; System.out.println(a.split(",").length); //結果為4 String a = "a,a,,"; System.out.println(a.split(",").length); //結果為2 String a = "a,a,a,"; System.out.println(a.split(",").length); //結果為3 String a = ",a,a,a"; System.out.println(a.split(",").length); //結果為4
```
從以上代碼可以得出:當后面的逗號都為空的時候撤嫩,默認是沒有的蹋订,split函數(shù)就不會再進行切割了。
split源碼探究
```
public String[] split(CharSequence input [, int limit]) { int index = 0; // 指針 boolean matchLimited = limit > 0; // 是否限制匹配個數(shù)?
?ArrayListmatchList = new ArrayList(); // 匹配結果隊列
? ? Matcher m = matcher(input);? ? ? ? ? ? // 待切割字符(串)匹配對象,pattern去哪了敦第?
? ? // Add segments before each match found
? ? while(m.find()) {
? ? ? ? if (!matchLimited || matchList.size() < limit - 1) {? // 如果不限制匹配個數(shù) 或者 當前結果列表的大小小于limit-1
? ? ? ? ? ? String match = input.subSequence(index, m.start()).toString();? // 取子串,(指針位置彰导,分隔串所在的首位)
? ? ? ? ? ? matchList.add(match);? ? ? // 添加進結果集
? ? ? ? ? ? index = m.end();? ? ? ? ? // 移動指針
? ? ? ? } else if (matchList.size() == limit - 1) { // last one矢腻,即還剩最后一個名額了
? ? ? ? ? ? String match = input.subSequence(index, input.length()).toString();? // 最后一個元素從指針取到字符串結尾
? ? ? ? ? ? matchList.add(match);
? ? ? ? ? ? index = m.end();
? ? ? ? }
? ? }
? ? // If no match was found, return this
? ? if (index == 0)? // 即沒有切分到的意思吧,返回整一串
? ? ? ? return new String[] {input.toString()};
? ? // Add remaining segment
? ? if (!matchLimited || matchList.size() < limit)? // 如果不限制匹配個數(shù) 或者 結果集大小小于限制個數(shù)
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? // 這個時候学搜,后面已無匹配娃善,如__1_1___,取最后一個1的后面部分
? ? ? ? matchList.add(input.subSequence(index, input.length()).toString());? // 最后一個元素從指針取到字符串結尾
? ? // Construct result
? ? int resultSize = matchList.size();
? ? if (limit == 0)
? ? ? ? while (resultSize > 0 && matchList.get(resultSize-1).equals(""))? // 如果結果集最后的元素是""瑞佩,一個一個地刪除它們
? ? ? ? ? ? resultSize--;
? ? String[] result = new String[resultSize];
? ? return matchList.subList(0, resultSize).toArray(result);
}
```
?特別地聚磺,最后的while循環(huán)里,把結果集的位于最后的""元素刪除了炬丸,有人問過“boo:and:foo”用“o”來分割瘫寝,為什么結果是{“b”,"",":and:f"}驾锰,而不是{"b","",":and:f","",""}的原因所在了屉来。