Program to count no of words in a given string | Count the no of words in a given string in C++ | How to count no of words in a string

Program to count no words in a given string 

Code

#include <bits/stdc++.h>
using namespace std;


int main() {
    cout<<
"Enter a String: "<<endl;                  //requesting a string
    string s;
    getline(cin,s);                                                         //to read space separated input
    
    int count=1;                                                             //setting count to 1 
    
    for(int i=0;i<s.length();i++){                                        //loop to count words
        if(s[i]==' '){
            count++;
        }
    }
    
    cout<<"No of words: "<<count<<endl;                 //printing the required output
    
    return 0;
}


Note: Count is set to 1 as last word won't have space after it.


Input:

Enter a String: 

My name is Lakhan

Output:

No of words: 4



Post a Comment

0 Comments