Count words in C lang

Previously we showed how to count words in java.
Now we will demonstrate how to count words in C lang.

First, read the entered string and initialize to s using gets(s).
We are finding the word count based on the given string’s white spaces. The ASCII value of white space is 32.
For loop iterates through the string with the structure for(i=0;s[i];i++)
If ASCII value of any string character is equal to ASCII value of white space, i.e., 32, then increase the word count.

After all iterations of for loop increase the word count, if i>0.

#include <stdio.h>
#include <string.h>

int main() {
    char s[1000];
    int i,words=0;

    printf("Enter  the string : ");
    gets(s);

    for(i=0;s[i];i++) {
    	if(s[i]==32){
            words++;
    	}
     }
     if(i>0) {
        words++;
     }
    printf("no of words in string = %d\n",words);

    return 0;
}

You can try the Word Frequency tool, an online tool for counting words in a text. In addition to having other amazing features.

Leave a Reply

Your email address will not be published. Required fields are marked *