首页 > 其他 > 详细

如何统计一个字符串中某个字符出现的次数

时间:2020-04-10 17:54:00      阅读:80      评论:0      收藏:0      [点我收藏+]

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

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);
}

如何统计一个字符串中某个字符出现的次数

原文:https://www.cnblogs.com/caozx/p/12455133.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!