Java 使用Regex计算一个给定字符的出现次数
给定一个字符串和一个字符,任务是使用Regex制作一个函数来计算字符串中给定字符的出现次数。
例子
**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.
正则表达式
正则表达式或Regex是一个定义字符串模式的API,可用于在Java中搜索、操作和编辑字符串。电子邮件验证和密码是广泛使用Regex来定义约束条件的几个字符串领域。正则表达式是在 java.util.regex 包下提供的。
方法 -在Java Regex中使用Matcher.find()方法
- 获取要匹配的字符串
- 使用Matcher.find()函数(在Java中)找到所有给定字符的出现次数
- 每找到一次,就把计数器增加1。
下面是上述方法的实现。
// Java program to count occurrences
// of a character using Regex
import java.util.regex.*;
class GFG {
// Method that returns the count of the given
// character in the string
public static long count(String s, char ch)
{
// Use Matcher class of java.util.regex
// to match the character
Matcher matcher
= Pattern.compile(String.valueOf(ch))
.matcher(s);
int res = 0;
// for every presence of character ch
// increment the counter res by 1
while (matcher.find()) {
res++;
}
return res;
}
// Driver method
public static void main(String args[])
{
String str = "geeksforgeeks";
char c = 'e';
System.out.println("The occurrence of " + c + " in "
+ str + " is " + count(str, c));
}
}
输出
The occurrence of e in geeksforgeeks is 4