Q:

C++ Program to Count Number of Words (Words Counter) in String

0
Explanation:- c++ word frequency counter is different from the counting the character in a string, as we know that the words are a group of two or more character and words are separated from white space so we have to count the total number of words in a string.
So basically idea is to count the characters between two spaces in a given string or sentence, from starting to next space counter will be 1 and for next space to next to next space increase the counter by one now counter is two and so on until program reached to second last space to NULL character in string or sentence.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include<iostream>
#include<conio.h>
#include<cstring>
using namespace std;
int main()
{
 char str[100],a;
 int w=0,l,c=0,j, i;

 cout<<"\nPlease Enter A String: \n\n";
 gets(str);

 for(i=0;i<100;i++)
     if(str[i]==' ')
       c++;
     else
         break;

 for(j=c;str[j]!='\0';j++)
 {
  if(str[j]==' ' && str[j+1]!=' ')
   w++;
 }

 if(str[j-1]==' ')
    w--;
 
 cout<<w+1;

 return 0;
}

 

Output:

Please Enter A String: 

c++ programming

2

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< C++ Program to Display String From Backward...