Count occurrences of a word in string | Set 2 (Using Regular Expressions) Last Updated : 15 Feb, 2023 Comments Improve Suggest changes Like Article Like Report Given a string str and a word w, the task is to print the number of the occurrence of the given word in the string str using Regular Expression. Examples: Input: str = "peter parker picked a peck of pickled peppers”, w = "peck"Output: 1Explanation: There is only one occurrence of the word "peck" in the given string. Therefore, the output is 1. Input: str = "How much wood would a woodchuck chuck if a woodchuck could chuck wood ?", w = "wood"Output: 2Explanation: There are only two occurrences of the word "wood" in the given string. Therefore, the output is 2. Input: str = "She sells seashells by the seashore", w = "sea"Output: 0Explanation: There is no occurrence of the word "sea" in the given string. Therefore, the output is 0. Approach: The required regular expression to find the required count of string w in the given string is "\\bw\\b", where \b is a word boundary. Follow the steps to solve the problem Create the regular expression pattern for the word w regex = "\\bw\\b" Traverse the string, match the regex with the string str using regex_iterator(). Simultaneously, update number of matches. Print the total number of matches obtained in the above step. Below is the implementation of the above approach : C++ // C++ program for the above approach #include <iostream> #include <regex> using namespace std; // Function to count total occurrences // of word "w" in string "str" void countOccurrences(string str, string w) { // Get the regex to be checked string regexPattern = "\\b" + w + "\\b"; const regex pattern(regexPattern); // Variable to count total // occurrences of the given word int count = 0; auto it = sregex_iterator(str.begin(), str.end(), pattern); for (it; it != sregex_iterator(); it++) { // Increment count count++; } // Print the occurrences of the word cout << count << endl; return; } // Driver Code int main() { // Input string str = "peter parker picked a peck of pickled peppers"; string w = "peck"; countOccurrences(str, w); return 0; } Java // Java program for the above approach import java.util.*; import java.util.regex.*; class GFG { // Function to count total occurrences // of word "w" in String "str" static void countOccurrences(String str, String w) { // Get the regex to be checked String regexPattern = "\\b" + w + "\\b"; Pattern pattern = Pattern.compile(regexPattern); // Variable to count total // occurrences of the given word int count = 0; while (str.contains(w)) { str = str.replace(w, ""); // Increment count count++; } // Print the occurrences of the word System.out.print(count + "\n"); return; } // Driver Code public static void main(String[] args) { // Input String str = "peter parker picked a peck of pickled peppers"; String w = "peck"; countOccurrences(str, w); } } // This code is contributed by gauravrajput1 Python3 # Python program for the above approach import re # Function to count total occurrences # of word "w" in String "str" def countOccurrences(str,w): # Get the regex to be checked regexPattern = "\\b" + w + "\\b" # Variable to count total # occurrences of the given word count=0 for m in re.finditer(regexPattern, str): # Increment count count=count+1 # Print the occurrences of the word print(count) # Driver Code # Input str = "peter parker picked a peck of pickled peppers" w = "peck" countOccurrences(str,w) # This code is contributed by Pushpesh Raj. C# // C# program for the above approach using System; using System.Text.RegularExpressions; public class GFG { // Function to count total occurrences // of word "w" in String "str" static void countOccurrences(String str, String w) { // Get the regex to be checked String regexPattern = "\\b" + w + "\\b"; Regex rx = new Regex(regexPattern,RegexOptions.Compiled | RegexOptions.IgnoreCase); // Variable to count total // occurrences of the given word int count = 0; while (str.Contains(w)) { str = str.Replace(w, ""); // Increment count count++; } // Print the occurrences of the word Console.Write(count + "\n"); return; } // Driver Code public static void Main(String[] args) { // Input String str = "peter parker picked a peck of pickled peppers"; String w = "peck"; countOccurrences(str, w); } } // This code is contributed by gauravrajput1 JavaScript //// Javascript program for the above approach function countOccurrences(string, substring) { var n = 0; var position = 0; while (true) { position = string.indexOf(substring, position); if (position != -1) { n++; position += substring.length; } else { break; } } return n; } console.log(countOccurrences("peter parker picked a peck of pickled peppers", "peck")); // This code is contributed By Rahul Chauhan Output1 Time Complexity : O(N)Auxiliary Space : O(N) Comment More infoAdvertise with us Next Article Count occurrences of a word in string | Set 2 (Using Regular Expressions) yuvraj_chandra Follow Improve Article Tags : Strings Pattern Searching C++ DSA CPP-regex regular-expression +2 More Practice Tags : CPPPattern SearchingStrings Similar Reads Count occurrences of strings formed using words in another string Given a string A and a vector of strings B, the task is to count the number of strings in vector B that only contains the words from A. Examples: Input: A="blue green red yellow"B[]={"blue red", "green pink", "yellow green"}Output: 2 Input: A="apple banana pear"B[]={"apple", "banana apple", "pear ba 7 min read Count occurrences of a word in string Given a two strings s and word. The task is to count the number of occurrences of the string word in the string s.Note: The string word should appear in s as a separate word, not as a substring within other words.Examples: Input: s = "GeeksforGeeks A computer science portal for geeks", word = "porta 11 min read Count occurrence of a given character in a string using Stream API 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 Stream API. Examples: Input: str = "geeksforgeeks", c = 'e' Output: 4 'e' appears four times in str. Input: str = "abccdefgaa", c = 'a' Output: 3 'a' appears three ti 1 min read Find all the patterns of "1(0+)1" in a given string using Regular Expression In Set 1, we have discussed general approach for counting the patterns of the form 1(0+)1 where (0+) represents any non-empty consecutive sequence of 0âs.In this post, we will discuss regular expression approach to count the same. Examples: Input : 1101001 Output : 2 Input : 100001abc101 Output : 2 3 min read Count the number of vowels occurring in all the substrings of given string | Set 2 Given a string str[] of length N of lowercase characters containing 0 or more vowels, the task is to find the count of vowels that occurred in all the substrings of the given string. Examples: Input: str = âabcâ Output: 3The given string âabcâ contains only one vowel = âaâ Substrings of âabcâ are = 5 min read Count Occurrences of a Given Character in a String Given a string S and a character 'c', the task is to count the occurrence of the given character in the string.Examples: Input : S = "geeksforgeeks" and c = 'e'Output : 4Explanation: 'e' appears four times in str.Input : S = "abccdefgaa" and c = 'a' Output : 3Explanation: 'a' appears three times in 6 min read Count occurrences of substring X before every occurrence of substring Y in a given string Given three strings S, X, and Y consisting of N, A, and B characters respectively, the task is to find the number of occurrences of the substring X before every occurrence of the substring Y in the given string S. Examples: Input S = âabcdefdefabcâ, X = âdefâ, Y = âabcâOutput: 0 2Explanation:First o 6 min read Generate Two Output Strings Depending upon Occurrence of Character in Input String - Python The task of generating two output strings based on the occurrence of characters in an input string in Python involves classifying characters based on their frequency. We need to create one string that contains characters that appear only once in the input string and another string for characters tha 4 min read Count occurrences of a sub-string with one variable character Given two strings a and b, and an integer k which is the index in b at which the character can be changed to any other character, the task is to check if b is a sub-string in a and print out how many times b occurs in a in total after replacing the b[k] with every possible lowercase character of Eng 5 min read Count words present in a string Given an array of words and a string, we need to count all words that are present in given string. Examples: Input : words[] = { "welcome", "to", "geeks", "portal"} str = "geeksforgeeks is a computer science portal for geeks." Output : 2 Two words "portal" and "geeks" is present in str. Input : word 6 min read Like