Java 使用Stream API计算字符串中给定字符的出现次数
给定一个字符串和一个字符,任务是使用Stream API制作一个函数来计算字符串中给定字符的出现次数。
例子
输入: str = “geeksforgeeks”, c = ‘e’
输出: 4
‘e’ appears four times in str.
输入: str = “abccdefgaa”, c = ‘a’
输出: 3
‘a’ appears three times in str.
建议:请先在 {IDE}上尝试你的方法,然后再继续解决。
办法。
- 将字符串转换为字符流
- 使用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