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

原文:https://www.studytonight.com/java-examples/count-occurrences-of-a-character-in-java

字符串只是一个字符序列。在本教程中,我们将学习统计字符串中特定字符出现次数的不同方法。

方法 1 -迭代方法

我们将遍历字符串中的每个字符。如果这个字符与我们正在寻找的字符匹配,我们将增加一个计数。下面的代码演示了这种方法。

public static int countChars(String str, char c)
{
    int count = 0;

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

    return count;
}

让我们使用这个方法,并检查它是否给出理想的输出。

public static void main(String[] args)
{
    String s = "Java is an awesome language!";
    int charCountOfA = countChars(s, 'a');
    int charCountOfG = countChars(s, 'g');
    int charCountOfE = countChars(s, 'e');

    System.out.println("The String is: " + s);
    System.out.println("Character count of 'a': " + charCountOfA);
    System.out.println("Character count of 'g': " + charCountOfG);
    System.out.println("Character count of 'e': " + charCountOfE);
}

字符串是:Java 是一门牛逼的语言! 字符数“a”:6 字符数“g”:2 字符数“e”:3

方法 2 -递归方法

看到这个问题,递归不会是第一个想到的。但是,我们可以用递归来解决这个问题。我们将使用两种方法而不是一种。第一个方法是递归的,第二个方法调用第一个方法。该方法与上一节中讨论的方法非常相似。

public static int countCharsRecur(String str, char c, int idx)
{
    if(idx >= str.length())
        return 0;

    else {
        int count = 0;
        if(str.charAt(idx) == c)
            count = 1;
        return count + countCharsRecur(str, c, idx + 1);
    }
}

public static int countChars(String s, char c)
{
    return countCharsRecur(s, c, 0);
}

让我们使用上述方法并查看输出。

public static void main(String[] args)
{
    String s = "Java is an awesome language!";
    int charCountOfA = countChars(s, 'a');
    int charCountOfG = countChars(s, 'g');
    int charCountOfE = countChars(s, 'e');

    System.out.println("The String is: " + s);
    System.out.println("Character count of 'a': " + charCountOfA);
    System.out.println("Character count of 'g': " + charCountOfG);
    System.out.println("Character count of 'e': " + charCountOfE);
}

字符串是:Java 是一门牛逼的语言! 字符数“a”:6 字符数“g”:2 字符数“e”:3

方法 3 -使用 Java 8 流

Java 8 Streams 还提供了一种简单的方法来计算字符串中字符的出现次数。我们将首先使用 chars()方法将字符串转换为一个输入流。我们也可以使用 codePoints()方法来代替 chars()。接下来,我们将使用带有 Lambda 表达式的 filter()方法来过滤掉所有匹配的字符。最后,我们将使用 count()方法返回过滤流中元素的计数。

public class Demo
{    
    public static void main(String[] args)
    {
        String s = "Java is an awesome language!";
        int charCountOfA = (int) s.chars().filter(c -> c == 'a').count();
        int charCountOfG = (int) s.chars().filter(c -> c == 'g').count();
        int charCountOfE = (int) s.chars().filter(c -> c == 'e').count();

        System.out.println("The String is: " + s);
        System.out.println("Character count of 'a': " + charCountOfA);
        System.out.println("Character count of 'g': " + charCountOfG);
        System.out.println("Character count of 'e': " + charCountOfE);
    }
}

字符串是:Java 是一门牛逼的语言! 字符数“a”:6 字符数“g”:2 字符数“e”:3

方法 4 -使用正则表达式

正则表达式也可以解决这个问题。然而,用正则表达式来解决这样一个简单的问题并不是一个好主意。下面的代码演示了如何使用正则表达式来解决这个问题。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo
{    
    public static int countChars(String str, char c)
    {
        String regex = String.valueOf(c);
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        int count = 0;
        while(matcher.find())
            count += 1;
        return count;
    }    
    public static void main(String[] args)
    {
        String s = "Java is an awesome language!";
        int charCountOfA = countChars(s, 'a');
        int charCountOfG = countChars(s, 'g');
        int charCountOfE = countChars(s, 'e');

        System.out.println("The String is: " + s);
        System.out.println("Character count of 'a': " + charCountOfA);
        System.out.println("Character count of 'g': " + charCountOfG);
        System.out.println("Character count of 'e': " + charCountOfE);
    }
}

字符串是:Java 是一门牛逼的语言! 字符数“a”:6 字符数“g”:2 字符数“e”:3

方法 5 -外部库

计算字符串中某个字符的出现次数是非常常见的,以至于许多外部库都有内置函数来实现这一点。让我们使用一些外部库来解决这个问题。

使用番石榴图书馆

番石榴库提供了 CharMatcher 类,可以计算给定字符出现的次数。首先,我们将使用这个类的静态 is() 方法。此方法创建一个 CharMatcher 实例来匹配特定的字符。接下来,我们将使用 countIn() 方法,该方法将一个字符串作为参数,并返回该字符串中字符的计数。

import com.google.common.base.CharMatcher;

public class Demo
{    
    public static void main(String[] args)
    {
        String str = "Java is an awesome language!";
        CharMatcher cm = CharMatcher.is('a'); //Creating the CharMatcher
        int charCountOfA = cm.countIn(str); //Counting the occurences

        System.out.println("The String is: " + str);
        System.out.println("Character count of 'a': " + charCountOfA);
    }
}

字符串是:Java 是一门牛逼的语言! 字符数“a”:6

使用阿帕奇图书馆

阿帕奇公共库提供了一个String类。这个类有一个方便的 countMatches() 方法,该方法将一个字符和一个字符串作为输入,并将该字符串中的字符计数作为输出返回。

import org.apache.commons.lang3.StringUtils;

public class Demo
{    
    public static void main(String[] args)
    {
        String s = "Java is an awesome language!";
        int charCountOfA = StringUtils.countMatches(s, 'a');
        int charCountOfG = StringUtils.countMatches(s, 'g');
        int charCountOfE = StringUtils.countMatches(s, 'e');

        System.out.println("The String is: " + s);
        System.out.println("Character count of 'a': " + charCountOfA);
        System.out.println("Character count of 'g': " + charCountOfG);
        System.out.println("Character count of 'e': " + charCountOfE);
    }
}

字符串是:Java 是一门牛逼的语言! 字符数“a”:6 字符数“g”:2 字符数“e”:3

摘要

计算字符串中某个字符的出现次数是一项非常简单的任务。我们可以使用核心 Java 迭代或递归地解决这个问题。流也可以在一行代码中解决这个问题。我们也可以使用正则表达式,但是它们提供了次优的解决方案。