日期:2014-05-17 浏览次数:20855 次
Pattern p = Pattern.compile(","); Matcher m = p.matcher("aaa,sss,bbb,ccc,aaa"); int c=0,index=-1; while(m.find()){ c++; index=m.start(); if(c==3){System.out.println(index);return;} }
------解决方案--------------------
public class Test { /** * @param args */ public static void main(String[] args) { String s = "asaa,ssdds,bbb,cffcc,aaa"; System.out.println(getIndex(s, ",", 4)); } public static int getIndex(String str, String c, int times) { int index = 0; String[] arr = str.split(c); int length = arr.length > times ? times : arr.length; for (int i = 0; i < length; i++) { index += arr[i].length(); } return index + times - 1; } }
------解决方案--------------------
public static void main(String[] args) { //方法1、正则匹配 int num = 0; String s = "aaa,sss,bbb,ccc,aaa"; Pattern p = Pattern.compile(","); Matcher m = p.matcher(s); while(m.find()){ num++; if(3 == num){ System.out.println(m.start()); } } //方法2,用String的indexOf方法,每找到一个“,”,就将字符串截取, //直到找到第三个,将每次下标累加即可。 num = 0; String s1 = "aaa,sss,bbb,ccc,aaa"; int location = 0; int index = s1.indexOf(","); while(-1 != s1.indexOf(",")){ location += index; num++; if(3 == num){ System.out.println(location); break; }else{ s1 = s1.substring(index,s1.length()); index = s1.indexOf(",",1); } } }