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.
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 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:
The occurrence of e in geeksforgeeks is 4
- Program to count the occurrence of a given character in a string
- Count occurrence of a given character in a string using Stream API in Java