日期:2014-05-17  浏览次数:20896 次

java中如何查询一个指定的子字符在字符串中出现的指定次数的下标索引
如题 比如 有这么一个字符串“aaa,sss,bbb,ccc,aaa”
我想知道“,”出现第三次时的下标是多少

------解决方案--------------------
对字符串进行遍历吧。
或是按‘,’split一下。再将前三个字符串的长度求和
------解决方案--------------------
Java code

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;}
}

------解决方案--------------------
Java code

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;
    }
}

------解决方案--------------------
Java code


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);
            }
        }
    }