如何计算一个字符在 Java 字符串中的出现次数

原文:https://www.studytonight.com/java-examples/how-to-count-occurrence-of-a-char-in-java-string

在这篇文章中,我们将使用 Java 代码计算字符串中某个字符的出现次数。字符串是一个字符序列,也可以包含重复的字符。

因此,如果任何字符串包含一个字符不止一次,并且我们想要检查该字符的出现,那么我们可以使用 String 类的几种方法来帮助找到字符频率。

这里,我们使用replace()charAt()filter()方法来查找字符串中存在的字符。

举例时间:

让我们创建一个示例来查找字符串中出现的字符。这里,我们使用的是replace()方法,它只返回一个包含‘a’的字符串,然后两个字符串长度的差就是结果。replace()方法并不意味着查找字符出现,但是我们可以使用它来构建一些逻辑代码,从而产生所需的结果。

public class Main {
    public static void main(String[] args){
        String str = "abracadabra-banana";
        System.out.println(str);
        // count occurrence 
        int count = str.length() - str.replace("a", "").length();
        System.out.println("occurrence of a: "+count);
    }
}

阿布拉卡达布拉-香蕉 的发生率为:8

示例:Java 8

我们再举一个例子来寻找字符频率。这里,我们使用返回流的chars()方法,然后使用filter()方法获取字符串中存在的所有‘a’count()方法用于计算过滤后的流。这里我们使用的是 Java 8 版本的 流 API 概念,请看下面的例子。

public class Main {
    public static void main(String[] args){
        String str = "abracadabra-banana";
        System.out.println(str);
        // count occurrence 
        long count = str.chars().filter(ch -> ch == 'a').count();
        System.out.println("occurrence of a: "+count);
    }
}

阿布拉卡达布拉-香蕉 的发生率为:8

示例:自定义代码

这是在字符串中查找字符数的常规解决方案。这里,我们使用一个循环遍历字符串中的每个字符,并通过使用charAt()方法比较字符,该方法返回指定索引处的字符,最后计算一个字符是否与所需的字符匹配。

public class Main {
    public static void main(String[] args){
        String str = "abracadabra-banana";
        System.out.println(str);
        // count occurrence 
        int count = 0;
        for (int i=0; i < str.length(); i++)
        {
            if (str.charAt(i) == 'a')
            {
                 count++;
            }
        }
        System.out.println("occurrence of a: "+count);
    }
}

阿布拉卡达布拉-香蕉 的发生率为:8