📌  相关文章
📜  使用Java中的 Stream API 计算字符串中给定字符的出现次数

📅  最后修改于: 2022-05-13 01:55:43.366000             🧑  作者: Mango

使用Java中的 Stream API 计算字符串中给定字符的出现次数

给定一个字符串和一个字符,任务是创建一个函数,使用 Stream API 计算字符串中给定字符的出现次数。

例子:

Input: str = "geeksforgeeks", c = 'e'
Output: 4
'e' appears four times in str.

Input: str = "abccdefgaa", c = 'a' 
Output: 3
'a' appears three times in str.

方法:

  • 将字符串转换为字符流
  • 使用 filter()函数检查流中的字符是否是要计数的字符。
  • 使用 count()函数计算匹配的字符

下面是上述方法的实现:

// Java program to count occurrences
// of a character using Stream
  
import java.util.stream.*;
  
class GFG {
  
    // Method that returns the count of the given
    // character in the string
    public static long count(String s, char ch)
    {
  
        return s.chars()
            .filter(c -> c == ch)
            .count();
    }
  
    // Driver method
    public static void main(String args[])
    {
        String str = "geeksforgeeks";
        char c = 'e';
        System.out.println(count(str, c));
    }
}
输出:
4

相关文章:计算字符串中给定字符出现次数的程序