Java查询一个字符串a出现在另一个字符串b中的次数

复杂纯原生:

    int get(String a,String b){
        int count=0;
        char[] aa=a.toCharArray();
        char[] bb=b.toCharArray();
        if(aa.length>bb.length)return 0;
        for(int i=0;i=bb.length){
                    success=false;
                    break;
                }
                if(aa[j]==bb[sign]) {
                    sign++;
                }else{
                    success=false;
                    break;
                }
            }
            if(success)count++;
        }
        return count;
    }

利用String自带函数:

    int get2(String a,String b) {
        int num = 0;
        while (b.contains(a)) {
            b=b.substring(b.indexOf(a)+1);
            num++;
        }
        return num;
    }

区别在于第一个看起来代码很多,但都是最底层代码,执行快,第二个就比较慢,但是做小程序啥的还是可以忽略不计。

测试用例:

        long t1=System.nanoTime();
        int q1=get("abcabcabcab","abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc");
        long t2=System.nanoTime();
        System.out.println("q1="+q1+",t1="+t1+",t2="+t2+",差="+(t2-t1));
        t1=System.nanoTime();
        q1=get2("abcabcabcab","abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc");
        t2=System.nanoTime();
        System.out.println("q1="+q1+",t1="+t1+",t2="+t2+",差="+(t2-t1));

结果:(单位:纳秒)q1是统计次数

q1=29,t1=649577234634600,t2=649577234657100,差=22500
q1=29,t1=649577272519200,t2=649577272578900,差=59700

 

 

 

你可能感兴趣的:(Java,java,字符串)