統計字符串中某個字符的出現次數


引言:統計字符串中某個字符的出現次數其實可以直接使用apache commons lang包中的StringUtils.countMatches()方法,但覺得寫的有點麻煩了,就自己實現了一個完成類似功能簡單的方法

1. 不廢話,先代碼:

1、TestCountMatches 類:

package test;

public class TestCountMatches {

    public static void main(String[] args) {
        System.out.println(countMatched("abcdeeeee", "e"));
        System.out.println(countMatched("abcdeeab", "ab"));
    }

    /**
     * 統計出現次數
     * @param string 目標字符串
     * @param sub 目標子字符串
     * @return
     */
    public static int countMatched(String string, String sub){
        //判空,為空直接返回0,表示不存在
        if(StringUtil.isEmpty(string) || StringUtil.isEmpty(sub)){
            return 0;
        }
        int count = 0;
        int index;
        // 循環一次將出現的字符串索引向后移一位,計數器+1,並截取原字符串索引+1的字符串,
        // 如“abcdeeeee”第一次循環找到“e”索引4,substring(4+1)方法截取后得到新的字符串“eeee”,
        // 循環第二次找到“e”的索引0,substring(0+1)方法截取后得到新的字符串“eee”,,,以此類推
        while((index = string.indexOf(sub)) > -1){
            count++;
            string = string.substring(index + 1);
        }
        return count;
    }

}

2、StringUtil工具類:

package test;

public class StringUtil {

    /**
     * 判斷字符串是否為空
     * @param string
     * @return
     */
    public static boolean isEmpty(String string){
        if(string == null || "".equals(string.trim())){
            return true;
        }
        return false;
    }

}

運行結果

2. 再看一下Apache 提供的工具類apache commons lang方法countMatches():

public static int countMatches(final CharSequence str, final CharSequence sub) {
        if (isEmpty(str) || isEmpty(sub)) {
            return 0;
        }
        int count = 0;
        int idx = 0;
        while ((idx = CharSequenceUtils.indexOf(str, sub, idx)) != INDEX_NOT_FOUND) {
            count++;
            idx += sub.length();
        }
        return count;
    }

其實思路差不多,理解了最好自己動手寫一下


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM