天天看點

擷取指定字元串出現的次數

例如,擷取keyword在srctext中出現的次數?

方式一:

擷取指定字元串出現的次數

/** 

     *  

     * the number of occurrences of find keyword in srctext 

     * @param srctext 

     * @param keyword 

     * @return 

     */  

    public static int findstr1(string srctext, string keyword) {  

        int count = 0;  

        int leng = srctext.length();  

        int j = 0;  

        for (int i = 0; i < leng; i++) {  

            if (srctext.charat(i) == keyword.charat(j)) {  

                j++;  

                if (j == keyword.length()) {  

                    count++;  

                    j = 0;  

                }  

            } else {  

                i = i - j;// should rollback when not match  

                j = 0;  

            }  

        }  

        return count;  

    }  

方式二:

擷取指定字元串出現的次數

public static int findstr2(string srctext, string keyword) {  

        pattern p = pattern.compile(keyword);  

        matcher m = p.matcher(srctext);  

        while (m.find()) {  

            count++;  

方式三:

擷取指定字元串出現的次數

public static int findstr3(string srctext, string keyword) {  

        return findstr(srctext, keyword, 0);  

    public static int findstr(string srctext, string keyword, int pos) {  

        int i, j, k = 0;  

        i = pos;  

        j = 0;  

        while (i < srctext.length() && j < keyword.length()) {  

                ++i;  

                ++j;  

                    k = k + 1;// k++  

                i = i - j + 1;  

        return k;  

    }