Counting words in a text input even if it is not well formed – CSKC
Sign In

Search

Solved Problem #CPP#2717    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

 

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

  Related ( ? ) :

#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

Created: 17-Jan-2018 18:21 | Updated: 3-Mar-2018 19:55|