📌  相关文章
📜  在Java中使用正则表达式计算给定字符的出现次数

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

在Java中使用正则表达式计算给定字符的出现次数

给定一个字符串和一个字符,任务是创建一个函数,使用正则表达式计算字符串中给定字符的出现次数。

例子:

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.

常用表达

正则表达式或正则表达式是一种用于定义字符串模式的 API,可用于在Java中搜索、操作和编辑字符串。电子邮件验证和密码是正则表达式广泛用于定义约束的几个字符串区域。正则表达式在Java.util.regex包下提供。

方法——在Java正则表达式中使用 Matcher.find() 方法

  • 获取要匹配的字符串
  • 使用 Matcher.find()函数查找给定字符的所有出现(在Java中)
  • 对于每个找到的事件,将计数器增加 1

下面是上述方法的实现:

Java
// 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

相关文章:

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