C Program to Count Number of Words In a String
Logic
1. Take input string from user.
2. Run for loop . Whenever you find space increase the count by 1.
3. Once the loop is complete print the count.
#include <stdio.h> void main() { char str[100]; // Declare string with a size of 100 int wordcount=0,i; printf("Enter a string"); fgets(str,100,stdin); // Word count logic begins for(i=0;str[i]!='\0';i++) { /* Check for consecutive space .*/ if(str[i]==' ' && str[i+1]!=' ') wordcount++; } /* Check whether, we don't press enter without entering any value*/ if(wordcount > 1){ printf(" Total number of words is %d",wordcount+1); }else{ printf("Please enter valid string"); } }
Output:
Enter a string : cquestions dot in
Total number of words is 3
If we dont give any input in your program, i.e., just press enter... The number of words will be counted as 1 not 0. Is there any way to resolve this bug?
ReplyDeleteThanks for pointing error, i have corrected it.
Deleteif consecutive spaces found the words are count without a word .......
ReplyDeletecheck it and give a new solution.......
Thanks. Solve the issue of word count when consecutive spaces are there.
ReplyDeleteHow do you resolve the issue without complexing the program when the input sentence starts with a blank space?
ReplyDeleteCheck this out!! Here's also a problem for first line's words count but resolved newline problem :)
ReplyDelete#include
#include
int words(const char sentence[ ])
{
int counted = 0; // result
// state:
const char* it = sentence;
int inword = 0;
do switch(*it) {
case '\0':
case ' ': case '\t': case '\n': case '\r':
if (inword) { inword = 0; counted++; }
break;
default: inword = 1;
} while(*it++);
return counted;
}
int main(int argc, const char *argv[])
{
int t,m, count;
char str[1001];
scanf("%d",&t);
for(m=0;m<=t;m++)
{
if(m==1) continue;
else{
gets(str);
printf("%d\n", words(str));
}
}
}