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


將字符串直接進行遍歷或者將字符串轉變為字符數組,然后進行遍歷:

public static void main(String[] args) {
    String str = "ABCDEFABC";
    char searchChar = 'B';

    int count = 0;
    char[] charArray = str.toCharArray();
    for (char item : charArray) {
        if (item == searchChar) {
            count++;
        }
    }
    System.out.println("字符" + searchChar + "出現的次數為" + count);
}

 換一種思路:使用replace()方法,很好理解,並且高效。

public static void main(String[] args) {
    String str = "ABCDEFABC";
    String searchChar = "B";
    int count = 0;

    int origialLength = str.length();
    str = str.replace(searchChar, "");
    int newLength = str.length();

    count = origialLength - newLength;

    System.out.println("字符" + searchChar + "出現的次數為" + count);
}


免責聲明!

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



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