for(String token:"==".split("=")){
System.out.println("token: "+token+" "+token.length());
}
System.out.println("###");
for(String token:" ==".split("=")){
System.out.println("token: "+token+" "+token.length());
}
System.out.println("###");
for(String token:"== ".split("=")){
System.out.println("token: "+token+" "+token.length());
}
运行结果是:
###
token: 1
###
token: 0
token: 0
token: 1
token: 1
###
token: 0
token: 0
token: 1
有点意外?
连续两个等号"=="用等号split后什么也没有;
在等号前加上一个空格,split后只有一个空格字符串(长度1)
在等号后面加上一个空格,split后有3个字符串,前两个为空串(长度0),最后一个是空格字符串。
为什么这样的呢?看一看split的源代码就知道了,String的split调用的是Pattern的split方法
代码比较明白:
首先通过正则表达式找到分割符号,比如=
然后根据分割符号的位置分割出字符串了。
最后
while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
resultSize--;
resultSize--;
做了一些处理,把最后连续的空字符串去掉
比如"==" 根据"="分出来3个空字符串,所以去掉后什么也没有了
比如"== " 分成3个字符串——空,空,空格
比如" ==" 分成3个字符串——空格,空,空,去掉后面的两个空串就是剩下一个空格了
那么"= ="分成来的数组的长度是多少呢?应该很容易了吧。
Pattern的split的代码 limit是分割的最大数组长度
public String[] split(CharSequence input, int limit) {
int index = 0;
boolean matchLimited = limit > 0;
ArrayList<String> matchList = new ArrayList<String>();
Matcher m = matcher(input);
// Add segments before each match found
while(m.find()) {
if (!matchLimited || matchList.size() < 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)
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);
}
int index = 0;
boolean matchLimited = limit > 0;
ArrayList<String> matchList = new ArrayList<String>();
Matcher m = matcher(input);
// Add segments before each match found
while(m.find()) {
if (!matchLimited || matchList.size() < 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)
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);
}