Count words in a user-input string in C
Solution 1
It's just that you're counting spaces, this would also be incorrect if the user ended the string with a bunch of spaces. Try something like this:
#include <stdio.h>
#include <string.h>
void main()
{
char s[200];
int count = 0, i;
int foundLetter = False;
printf("enter the string\n");
gets(s);
for (i = 0;i<strlen(s);i++)
{
if (s[i] == ' ')
foundLetter = False;
else
{
if (foundLetter == False)
count++;
foundLetter = True;
}
}
printf("number of words in given string are: %d\n", count);
}
As other users have commented, your program is susceptible to many other issues depending on the string inputed. The example I have posted assumes that anything that is not a space is a letter and if you find at least one letter, than that's a word. Instead of boolean values you could use a counter to make sure that the word is at least a certain length. You could also check to see that it is not a number or symbol by either writing your own regex function or using an existing one. As others have said there is a lot more you can do with this program, but I've provided an example to point you in the right direction.
Solution 2
You are counting the amount of non-words, but you should be counting the amount of words.
If a word is defined as a sequence of one or more letters, your code might go as:
for every character in the string
if the character is part of a word ( "the car's wheel" is three words )
increase the word count
while the character is part of a word, increment your pointer
Vasundhara Mehta
Updated on July 09, 2022Comments
-
Vasundhara Mehta almost 2 years
So, we were given this program in class. "Write a Program in C to count the number of words in a sentence input by the user." This is what i could come up with, but the number of words is always one less than what is the correct number. My teacher told everyone to just add 1 to the word count before printing it. I think it has a bug, if we don't enter any words, i.e. , press Enter instead of typing,the program suggested by my teacher would still give word count as 1 not 0. Do you know of any way to get proper word count without just adding 1 at the end? Code:
My code(giving 1 less than correct) :
#include <stdio.h> #include <string.h> void main() { char s[200]; int count = 0, i; printf("enter the string\n"); gets(s); for (i = 0;i<strlen(s);i++) { if (s[i] == ' ') count++; } printf("number of words in given string are: %d\n", count); }