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);
}
}
相关文章推荐
- Java替换字符串中的“\"”的处理方法(String.replaceAll的源码分析)
- String源码分析(一部分方法)
- String源码分析之Java中的String为什么是不可变的以及replace方法源码分析
- String源码分析之equals和hashcode方法
- String源码分析
- java.lang.String源码分析(1)
- 关于java中String常用的几个方法的源码(容易根据方法名想当然的理解方法)
- JDK源码之解读String最终类的equals()和hashcode()方法实现原理
- Monkey源码分析番外篇之Android注入事件的三种方法比较
- jQuery源码分析之buildFragment方法和clone方法
- JDK源码之解读String最终类的trim()方法实现原理
- javascript中String对象的slice()方法分析
- Java中的String为什么是不可变的? -- String源码分析
- [原创] jQuery源码分析-11 DOM遍历-Traversing-DOM遍历方法
- jQuery源码解读之removeClass()方法分析
- Java-- String源码分析
- Picasso源码分析(五):into方法追本溯源和责任链模式创建BitmapHunter
- Android源码分析工具及方法
- Qt之使用setWindowFlags方法遇到的问题(追踪进入QWidget的源码分析原因,最后用WINAPI解决问题)good
- STL 源码分析之string(一)基础篇