split(" ");
" a b c" 得到" ","a","b","c":
" a b c"得到" "," ","a","b","c":前面的空格一个都不会省略。
"a b c"得到"a"," ","b","c":中间空格省略一个。
后缀的空格全部省略。
不是以空格而是以某个String为划分依据时,现象相同。
split("a");
"aaab"得到" "," "," ","b"
"baab"得到"b"," ","b"
源码分析
public String[] split(CharSequence input [, int limit]) {
int index = 0; // 指针
boolean matchLimited = limit > 0; // 是否限制匹配个数
ArrayList<String> matchList = new ArrayList<String>(); // 匹配结果队列
Matcher m = matcher(input); // 待切割字符(串)匹配对象,pattern去哪了?
// Add segments before each match found
while(m.find()) {
if (!matchLimited || matchList.size() < limit - 1) { // 如果不限制匹配个数 或者 当前结果列表的大小小于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) // 如果不限制匹配个数 或者 结果集大小小于限制个数
// 这个时候,后面已无匹配,如__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);
}