I have used a trick to count a word in a sentence. If it is not first character and this character is an alphabet (a,b,c, .. etc)then I check just previous character. If the previous character is not an alphabet then number of words will be increased by one. At last we will check the last character to ensure the end of sentence. If last character is not alphabet then the number of words will be increased by one. For explanation let us consider the following sentence :
Tushar konna is the nick name of Shampa.
We will check this sentence character by character. Suppose we are checking for k (first character of konna)Now ask yourself –
Is it not first character ? Ans: YES
The previous character of k is not an alphabet . Is it true? Ans:YES
So, one word is counted. Thus while checking i (first character of is), one more character will be counted. In this approach number of words will be 7 while checking S (first character of Shampa). Now check . (last character of the sentence). Is it alphabet ? Ans: NO(it is full stop). So number of word will be increased by one. Thus the total number of word of Tushar konna is the nick name of Shampa. sentence is 8.
#include<stdio.h> #include<ctype.h> #include<string.h> int main() { char str[1000]; int i, len, count; while(gets(str)) { len=strlen(str); count=0; for(i=0;i<len;i++) if(i>0&&isalpha(str[i])==0&&isalpha(str[i-1])!=0) count++; if(isalpha(str[len])!=0) count++; printf("%d\n",count); } return 0; }
Next Previous