- C++ Programming Examples
- C++ Programming Examples
- C++: Hello World
- C++: Get Input
- C++: Print Integer
- C++: Add two numbers
- C++: Add, Sub, Multiply, Div
- C++: Add Digits
- C++: Find Average and Percentage
- C++: Find Arithmetic Mean
- C++: Sum of n Natural Numbers
- C++: Sum of n Numbers
- C++: Square's Area and Perimeter
- C++: Rectangle's Area and Perimeter
- C++: Triangle's Area and Perimeter
- C++: Area and Circumference
- C++: Find Simple Interest
- C++: Fahrenheit to Celsius
- C++: Celsius to Fahrenheit
- C++: Print Prime Numbers
- C++: Reverse a Number
- C++: Swap Two Numbers
- C++: Print Multiplication Table
- C++: Find Factorial of a Number
- C++: Find Factors of a Number
- C++: Find HCF and LCM
- C++: Create a Calculator
- C++: Count Digits in a Number
- C++: First and Last Digit Sum
- C++: Product of Number Digits
- C++: Sum of Squares of Digits
- C++: Interchange Digits of Number
- C++ if-else Programs
- C++: Check Even or Odd
- C++: Check Prime or Not
- C++: Check Alphabet or Not
- C++: Check Vowel or Not
- C++: Check Leap Year or Not
- C++: Check Reverse equals Original
- C++: Check Perfect Number
- C++: Check Palindrome or Not
- C++: Check Armstrong or Not
- C++: Divisibility Test
- C++: Find Labor Wage
- C++: Find Discounted Price
- C++: Find Shipping Charge
- C++: Find Telephone Bills
- C++: Calculate Student Grade
- C++: Largest of Two Numbers
- C++: Largest of Three Numbers
- C++ Number Conversion
- C++: Decimal to Binary
- C++: Decimal to Octal
- C++: Decimal to Hexadecimal
- C++: Binary to Decimal
- C++: Binary to Octal
- C++: Binary to Hexadecimal
- C++: Octal to Decimal
- C++: Octal to Binary
- C++: Octal to Hexadecimal
- C++: Hexadecimal to Decimal
- C++: Hexadecimal to Binary
- C++: Hexadecimal to Octal
- C++ Pattern Programs
- C++: Pattern Programs
- C++: Print Diamond Pattern
- C++: Print Floyd's Triangle
- C++: Print Pascal's Triangle
- C++ Array Programs
- C++: 1D Array Program
- C++: Linear Search
- C++: Binary Search
- C++: Largest Element in an Array
- C++: Smallest Element in an Array
- C++: Find Second Largest Element
- C++: Find Second Smallest Element
- C++: Sum of All Elements
- C++: Multiply All Elements
- C++: Element in Even Position
- C++: Element in Odd Position
- C++: Print Even Numbers in Array
- C++: Print Odd Numbers in Array
- C++: Count Even or Odd Numbers
- C++: Sum of Even or Odd Numbers
- C++: Count Positive, Negative, Zero
- C++: Reverse an Array
- C++: Insert an Element
- C++: Delete an Element
- C++: Merge two Arrays
- C++: Bubble Sort
- C++: Selection Sort
- C++: Insertion Sort
- C++: Common Elements
- C++: 2D Array Programs
- C++: Add Two Matrices
- C++: Subtract Two Matrices
- C++: Transpose Matrix
- C++: Multiply Two Matrices
- C++: 3D Array Programs
- C++ String Programs
- C++: Print String
- C++: Find String Length
- C++: Compare Two Strings
- C++: Copy String
- C++: String Concatenation
- C++: Reverse a String
- C++: Delete Vowels from a String
- C++: Delete a Word from a String
- C++: Count Characters in a String
- C++: Count Words in a String
- C++: Frequency of Words
- C++: Remove Spaces from Strings
- C++: Sort a String
- C++: Uppercase to Lowercase
- C++: Lowercase to Uppercase
- C++: Swap Two Strings
- C++: Check the Anagram or Not
- C++: Capitalize All Words in a String
- C++: Get Numbers from a String
- C++ File Programs
- C++: Read a File
- C++: Write Content to a File
- C++: Append Data to a File
- C++: Read and Display File
- C++: Copy a File
- C++: Merge Two Files
- Count Characters in a File
- C++: Capitalize Every Word
- C++: List Files in Directory
- C++: Delete a File
- C++: Encrypt and Decrypt a File
- C++ Misc Programs
- C++: Print ASCII Value
- C++: Add Binary Numbers
- C++: Generate Random Numbers
- C++: Print a Smiling Face
- C++: Days into Years and Months
- C++: Add Two Numbers using Pointer
- C++: Print Fibonacci Series
- C++: Generate Armstrong Numbers
- C++: Find nCr and nPr
- C++: Get IP Address
- C++: Print Date and Time
- C++: Shutdown and Restart Computer
- C++ Programming Tutorial
- C++ Tutorial
C++ program to count the occurrences of a word in a string
In this article, you will learn and get code to count occurrences of a word in a string in C++. Here is the list of programs available:
Determine the Frequency of a Word in a String
This program counts the occurrence of a word in a given string. But this program is best suited to find the frequency of a sub-string (without space) in a string (entered by the user). I'll tell you about the reason later on.
The question is: write a program in C++ that finds the frequency of a word (a sub-string) in a string. Here is its answer:
#include<iostream> #include<stdio.h> using namespace std; int main() { char str[200], word[20]; int i=0, j, temp, countW=0, chk; cout<<"Enter the String: "; gets(str); cout<<"Enter the Word: "; gets(word); while(str[i]!='\0') { temp = i; j=0; while(word[j]!='\0') { if(str[i]==word[j]) i++; j++; } chk = i-temp; if(chk==j) countW++; i = temp; i++; } cout<<"\nOccurrence of '"<<word<<"' = "<<countW; cout<<endl; return 0; }
This program was built and runs under the Code::Blocks IDE. Here is its sample run:
Now supply any string, say this was fresherearth and this is fresherearth, and then a word, say fresherearth to find the frequency or occurrence of the word fresherearth in the string. Here is the final snapshot of the sample run:
The dry run of the above program with user inputs of "this was fresherearth and this is fresherearth" as a string and "fresherearth" as a word goes like this:
- i = 0, countW = 0 are the initial values.
- When the user enters the string, then it gets stored in str in a way that:
- str[0]=t
- str[1]=h
- str[2]=i
- and so on up until
- str[45]=r
- Similarly, the entered word, say fresherearth gets stored in the word in this way:
- word[0]=c
- word[1]=o
- word[2]=d
- and so on up until
- word[11]=r
- Because the maximum length of a string and a word, str[] and word[], are 200 and 20, respectively. However, the entered string and word are only 46 and 12, respectively. So a null terminated character (\0) automatically gets assigned after the last character's index in both strings and words.
- Now that the while loop's condition, str[i]!='\0' or str[0]!='\0' or t!='\0', evaluates to true, program flow enters the loop.
- And either i or 0 is set to temp. So temp=0 and j=0
- The condition, word[j]!='\0' or word[0]!='\0' or c!='\0' evaluates to be true, therefore program flow goes inside the loop.
- And the condition of if, that is str[i]==word[j] or str[0]==word[0] or t==c evaluates to be false, therefore program flow does not go inside its body (if's body). So it just increments the value of j and goes back and evaluates the inner while loop's condition again.
- The process of evaluating this while loop continues until its condition evaluated to be false.
- When its condition evaluates to false, the value of i will be 0 and j = 12 after exiting this loop for the time being.
- Now, i-temp, 0-0, or 0 is set to chk.
- And the condition chk==j or 0==12 evaluates to be false; therefore, program flow does not go inside its (if's) body.
- Now the value of temp (0) gets initialized to i. So i=0
- And finally, the value of i gets incremented. So i=1
- Program flow goes back and evaluates the condition of the while loop again.
- This process continues until the condition of the outer while loop evaluates to be false.
- On continuing the evaluation, here are the values we'll get after each evaluation:
- temp=0 (before inner while), j=0 (before inner while), i=0 (after inner while), j=12 (after inner while), countW=0, i=1 (final)
- temp=1 (before inner while), j=0 (before inner while), i=1 (after inner while), j=12 (after inner while), countW=0, i=2 (final)
- Similarly temp=2, j=0, i=2, j=12, countW=0, i=3
- temp=3, j=0, i=4, j=12, countW=0, i=4
- temp=4, j=0, i=4, j=12, countW=0, i=5
- temp=5, j=0, i=5, j=12, countW=0, i=6
- temp=6, j=0, i=7, j=12, countW=0, i=7
- temp=7, j=0, i=8, j=12, countW=0, i=8
- temp=8, j=0, i=8, j=12, countW=0, i=9
- temp=9, j=0, i=21, j=12, countW=1, i=10
- temp=10, j=0, i=21, j=12, countW=1, i=11
- and so on upto
- temp=45, j=0, i=46, j=12, countW=2, i=46
- Now print the value of countW as output; that will be the result.
Modified Version of the Previous Program
If your only goal is to count the occurrences of a word (without regard for the entire word) in a given string, the previous program is correct; otherwise, if you want to find the frequency of a single word in a string, the above program has a limitation, which is listed below.
Important: The above program has the limitation that it increments the value of countW if the entered word appears in any other word in the string. For example, if the string is "this is fresherearth" and the entered word is "is," Therefore, this also gets counted.
Here is the snapshot of the sample run (of the previous program) that clarifies what I mean to say:
So to improve the previous program, here is the modified version of that program:
#include<iostream> #include<stdio.h> #include<string.h> using namespace std; int main() { char str[100], word[20]; int i, j, ls, lw, k, countWord=0, chk, doIncrement; cout<<"Enter the String: "; gets(str); cout<<"Enter the Word: "; gets(word); ls = strlen(str); lw = strlen(word); for(i=0; i<ls; i++) { k = i; doIncrement = 0; for(j=0; j<lw; j++) { if(str[i]==word[j]) { if(k>0 && (k+lw)<ls) { if(str[k-1]== ' ' && str[k+lw]==' ') doIncrement=1; } else if(k==0 && (k+lw)<ls) { if(str[k+lw]==' ') doIncrement=1; } else if(k>0 && (k+lw)==ls) { if(str[k-1]== ' ') doIncrement=1; } if(doIncrement==1) i++; else break; } } chk = i-k; if(chk==lw) countWord++; i = k; } cout<<"\nOccurrence of '"<<word<<"' = "<<countWord; cout<<endl; return 0; }
Here is its sample run:
« Previous Program Next Program »