Count total Number of Words in the String

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

Example:

INPUT: 
Help Me Study Bro
OUTPUT:
4
INPUT:
Helpmestudybro is an emerging website.
OUTPUT:
5

The steps required to count total number of words in the 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 total number of words in the string is as follows:

#include<bits/stdc++.h>  
using namespace std;  
int main() 
{  
    string str;  
    cout<<"Enter a string:\n";  
    getline(cin,str);  
    int size = str.length();  
    int count = 0;  
    for(int i = 0; i < size; i++)  
    {  
        if(str[i] == ' ')  
        count++;  
    }  
    cout<<"Total number of words in the string are: "<<count+1;  
} 

OUTPUT:
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

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *