zoukankan      html  css  js  c++  java
  • 如何统计一个字符串中某个字符出现的次数

    将字符串直接进行遍历或者将字符串转变为字符数组,然后进行遍历:

    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);
    }
    
  • 相关阅读:
    命令[46]
    命令[53]
    命令[48]
    命令[43]
    命令[52]
    命令[55]
    命令[41]
    MYSQL[02]大小写问题
    hdu 1811
    hdu 1829
  • 原文地址:https://www.cnblogs.com/caozx/p/12455133.html
Copyright © 2011-2022 走看看