计算字符串中字符出现次数的简单方法

2022-08-31 13:24:32

有没有一种简单的方法(而不是手动遍历所有字符串,或循环indexOf)来查找字符串中出现了多少次字符?

假设我们有“abdsd3$asda$asasdd$sadas”,我们希望 $出现 3 次。


答案 1
public int countChar(String str, char c)
{
    int count = 0;

    for(int i=0; i < str.length(); i++)
    {    if(str.charAt(i) == c)
            count++;
    }

    return count;
}

这绝对是最快的方法。正则表达式在这里要慢得多,并且可能更难理解。


答案 2

函数式风格(Java 8,只是为了好玩):

str.chars().filter(num -> num == '$').count()