Count the total number of words in a string with C.
#include <stdio.h>
int main()
{
char str[100];
int i, words;
printf("Enter any string: ");
gets(str);
i = 0;
words = 1;
while (str[i] != '\0')
{
/* If the current character(str[i]) is white space */
if (str[i] == ' ' || str[i] == '\n' || str[i] == '\t')
{
words++;
}
i++;
}
printf("Total number of words = %d", words);
return 0;
}
Output
Enter any string : My name is Rezaul Karim
Total number of words = 5
0 Comments