字符串处理算法
原始字符串:String src= "1,2,3,4,5,6,7,8 "
场景1:String自有的方法public String [] split(String regex)
应用:String [] target=src.split( ", ")
结果:target=[ "1 ", "2 ", "3 ", "4 ", "5 ", "6 ", "7 ", "8 "]
场景二:要求扩展String自有的split(String regex)
定义函数 public String [] splitString(String src,String regx,int num)
应用:String [] target = splitString(src, ", ",3);
结果:target =[ "1,2,3 ", "4,5,6 ", "7,8 "]
我的思路是:先用String 自有的split方法分割,然后再重组成一个字符串数组,返回,但是感觉效率很低.
请教大家有什么好的算法;
------解决方案--------------------呵呵 是我脑子没转过来,修正如下:
public static String[] splitString(String src,String regex,int num) {
List <String> l = new ArrayList <String> ();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(src);
int beg = 0;
int count = 0;
while(m.find()) {
if(++count == num) {
l.add(src.substring(beg, m.start()));
beg = m.end();
count = 0 ;
}
}
if(beg <src.length())
l.add(src.substring(beg));
return l.toArray(new String[0]);
}