Count Occurrences of a Given Character using Regex in Java
Given a string and a character, the task is to make a function that counts the occurrence of the given character in the string using Regex.
Examples:
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.
Regular Expressions
Regular Expressions or Regex is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under java.util.regex package.
Approach – Using Matcher.find() method in Java Regex
- Get the String in which it is to be matched
- Find all occurrences of the given character using Matcher.find() function (in Java)
- For each found occurrence, increment the counter by 1
Below is the implementation of the above approach:
Java
import java.util.regex.*;
class GFG {
public static long count(String s, char ch)
{
Matcher matcher
= Pattern.compile(String.valueOf(ch))
.matcher(s);
int res = 0 ;
while (matcher.find()) {
res++;
}
return res;
}
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));
}
}
|
Output
The occurrence of e in geeksforgeeks is 4
Related Article:
Last Updated :
15 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...