Count occurrences of a given character using Regex in Java
Given a string and a character, the task is to make a function which counts the occurrence of the given character in the string using ReGex.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
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.
- 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 occurrences, increment the counter by 1
Below is the implementation of the above approach: