您的位置:首页 > 其它

String的spilt方法源码分析

2011-09-22 22:31 363 查看

/**
* String 类得split方法解析。
* 实际是调用Pattern类得split方法
*/
public class AboutSplit {
public String[] split(String regex, int limit) {
return Pattern.compile(regex).split("本String字符串", limit);
}
/**
* 关于limit:limit决定数组的长度
* 当limit为0时数组长度不受限制,并且将剔除尾部空串
* 当limit为负时数组长度不受限制
* 当limit长度大于0,数组长度将<=limit,而且数组的最后一个元素将包含匹配符后面的所有字符
*/
public String[] split(CharSequence input, int limit) {
int index = 0;
boolean matchLimited = limit > 0;
ArrayList<String> matchList = new ArrayList<String>();
Matcher m = Pattern.matcher(input); //此pattern为Pattern.compile(regex)返回的Pattern对象

// Add segments before each match found
while(m.find()) {
if (!matchLimited || matchList.size() < limit - 1) { //默认limit为0
String match = input.subSequence(index, m.start()).toString(); //比如a:b:c,返回a。m.start()返回第一个匹配字符的索引即1
matchList.add(match); //存入List
index = m.end(); //返回最后一个匹配字符的后一个字符的索引,这里是2
} else if (matchList.size() == limit - 1) { // 最后一个元素
String match = input.subSequence(index,
input.length()).toString();
matchList.add(match);
index = m.end();
}
}

// 没有找到匹配串
if (index == 0)
return new String[] {input.toString()};

// 把最后一部分的片段添加进来
if (!matchLimited || matchList.size() < limit)
matchList.add(input.subSequence(index, input.length()).toString());

// Construct result
int resultSize = matchList.size();
if (limit == 0) //如果limit为0
while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
resultSize--; //剔除尾部空串
String[] result = new String[resultSize];
return matchList.subList(0, resultSize).toArray(result);
}
}
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: