Count Number of Words in a String

Count Number of Words in a String” is a basic problem of string data structure. Here, we are given string containing some words and our task is to write a program to count the number of words present in the given string and print the count.


Help Me Study Bro

Helpmestudybro is an emerging website.

The steps required to Count Number of Words in a String is as follows:

  1. Scan the complete string.
  2. While scanning, keep count of every blank spaces encountered.(Each word of the string will be separated by blank space, obviously).
  3. The result will the count + 1.

C++ Program to Count Number of Words in a String is as follows:

/* Program to Count Number of Words in a String */
using namespace std;  
int main() 
    string str;  
    cout<<"Enter a string:\n";  
    int size = str.length();  
    int count = 0;  
    for(int i = 0; i < size; i++)  
        if(str[i] == ' ')  
    cout<<"Total number of words in the string are: "<<count+1;  

Enter a string: 
HelpMeStudyBro is an emerging website
Total number of words in the string are: 5
Time Complexity:
O(n), where n is the length of the string

Related Posts:

  1. Program to find smallest and largest word of the String.
  2. Program to find Most Frequent Character of the String.
  3. Program to Remove all the blank spaces from the String.
  4. Program to check if String is isogram or not.
  5. Program to Reverse Each word of the String.
  6. Program to Print All the Substring of the Given String.
  7. Program to find longest palindromic Substring.
  8. Program to check Anagram Strings.
  9. Program to check whether two Strings are Rotation of each other or not.
  10. Program to check Palindromic Anagram.
  11. Program to print all the Palindromic Substring of the String.
  12. Program to check Panagram String.
  13. Program to find first non-repeating character of the String.
  14. Merge Overlapping Intervals using Stacks
  15. Implement Stack Using Linked List
  16. Largest Rectangular Area in Histogram
  17. Length of Longest Valid Substring
  18. Reverse a String using Stack
  19. Implement two stacks in a single array
  20. Program to print kth smallest and kth largest element of an Array.

You may also like...