Java split方法源碼分析
1 public String[] split(CharSequence input [, int limit]) { 2 int index = 0; // 指針 3 boolean matchLimited = limit > 0; // 是否限制匹配個數 4 ArrayList<String> matchList = new ArrayList<String>(); // 匹配結果隊列 5 Matcher m = matcher(input); // 待切割字符(串)匹配對象,pattern去哪了? 6 7 // Add segments before each match found 8 while(m.find()) { 9 if (!matchLimited || matchList.size() < limit - 1) { // 如果不限制匹配個數 或者 當前結果列表的大小小於limit-1 10 String match = input.subSequence(index, m.start()).toString(); // 取子串,(指針位置,分隔串所在的首位) 11 matchList.add(match); // 添加進結果集 12 index = m.end(); // 移動指針 13 } else if (matchList.size() == limit - 1) { // last one,即還剩最后一個名額了 14 String match = input.subSequence(index, input.length()).toString(); // 最后一個元素從指針取到字符串結尾 15 matchList.add(match); 16 index = m.end(); 17 } 18 } 19 20 // If no match was found, return this 21 if (index == 0) // 即沒有切分到的意思吧,返回整一串 22 return new String[] {input.toString()}; 23 24 // Add remaining segment 25 if (!matchLimited || matchList.size() < limit) // 如果不限制匹配個數 或者 結果集大小小於限制個數 26 // 這個時候,后面已無匹配,如__1_1___,取最后一個1的后面部分 27 matchList.add(input.subSequence(index, input.length()).toString()); // 最后一個元素從指針取到字符串結尾 28 29 // Construct result 30 int resultSize = matchList.size(); 31 if (limit == 0) 32 while (resultSize > 0 && matchList.get(resultSize-1).equals("")) // 如果結果集最后的元素是"",一個一個地刪除它們 33 resultSize--; 34 String[] result = new String[resultSize]; 35 return matchList.subList(0, resultSize).toArray(result); 36 }
特別地,最后的while循環里,把結果集的位於最后的""元素刪除了,有人問過“boo:and:foo”用“o”來分割,為什么結果是{“b”,"",":and:f"},而不是{"b","",":and:f","",""}的原因所在了。