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.
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.
Approach:
- 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:
// 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(count(str, c)); } } |
chevron_right
filter_none
Output:
4
Related Article:
- Program to count occurrence of a given character in a string
- Count occurrence of a given character in a string using Stream API in Java
- Java program to count the occurrences of each character
- Count occurrences of elements of list in Java
- Count occurrence of a given character in a string using Stream API in Java
- Java program to count the occurrence of each character in a string using Hashmap
- Find the count of M character words which have at least one character repeated
- Regex Boundary Matchers in Java
- Java | Removing whitespaces using Regex
- Extracting each word from a String using Regex in Java
- Java | Date format validation using Regex
- Check if a string contains only alphabets in Java using Regex
- Get the first letter of each word in a string using regex in Java
- Remove all occurrences of an element from Array in Java
- Pattern Occurrences : Stack Implementation Java
- Java.lang.Character.Subset Class in Java
- Java.lang.Character.UnicodeBlock Class in Java
Recommended Posts:
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



