Counting words in a text input even if it is not well formed – Computer Sir Ki Class
  

Login
[lwa]



Solved Problem #CPP#2717 siteicon   siteicon   siteicon  

Problem Statement - Counting words in a text input even if it is not well formed

Write a program to count number of words even when there might be extra spaces between words and extra punctuation marks. Any alphabets or numbers written contiguously will be counted as words. For. e.g. “21st Century” are two words and “21    st         century systems ?” are four words. ? is not counted as word while 21 is counted as a word.

Solution

TC++ #2717

#include <iostream>
#include <ctype.h>
#include <conio.h>
int main()
{
clrscr();
char str[101];
cout<<"Input a sentence (Max. 100 chars): " ;
cin.getline(str,80);
int wc=0,j;
for(int i=0;str[i]!='';++i)
{
j=0;
while(isalnum(str[i]))
{
if(j==0) { wc++; j=1;}
++i;
}
}
cout <<"No. of words in given sentences = "<<wc<<endl;
getch();
return 0;
}
#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
char str[101];
cout<<"Input a sentence (Max. 100 chars): " ;
cin.getline(str,80);
int wc=0,j;
for(int i=0;str[i]!='';++i)
{
j=0;
while(isalnum(str[i]))
{
if(j==0) { wc++; j=1;}
++i;
}
}
cout <<"No. of words in given sentences = "<<wc<<endl;
return 0;
}


Test it !
  Related (?) :

Run Output

Input a sentence (Max. 100 chars): 21st Century : A Century of Services.
No. of words in given sentences = 6

#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
char str[101];
cout<<“Input a sentence (Max. 100 chars): ” ;
cin.getline(str,80);
int wc=0,j;
for(int i=0;str[i]!=”;++i)
{
j=0;
while(isalnum(str[i]))
{
if(j==0) { wc++; j=1;}
++i;
}
}
cout <<“No. of words in given sentences = “<<wc<<endl;
return 0;
}

 

Notes

  • This is a novel technique of words counting which you may not find in books. Please try this input with different kinds of sentences with numbers, punctuators, words with included numbers etc.
  • This technique is better than even professional word processing tools as it can ignore punctuation marks even when they have spaces in between words and punctuation marks.
  • This program also explains a novel looping technique where you can keep the loop count stay for some time until a particular condition is met. Such techniques are are useful when data is streaming from file or from any other streaming device.

Common Errors

  • The loop will not run well if the j flag is not reset before starting the internal loop.


Share

sunmitra| Created: 17-Jan-2018 | Updated: 3-Mar-2018|






Back