C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Count words in string

C Program: Count words in string

C

#include <stdio.h>

 

int main() {

    char str[200];

    int i, words = 0;

 

    // Input string safely

    printf("Enter a string: ");

    fgets(str, sizeof(str), stdin);  // safer than gets()

 

    // Traverse string to count words

    for (i = 0; str[i] != '\0'; i++) {

        // Check for word boundaries

        if ((str[i] == ' ' || str[i] == '\n' || str[i] == '\t') &&

            (str[i + 1] != ' ' && str[i + 1] != '\n' && str[i + 1] != '\t' && str[i + 1] != '\0'))

            words++;

    }

 

    // If string starts with a word (not a space)

    if (str[0] != ' ' && str[0] != '\n' && str[0] != '\t')

        words++;

 

    printf("Total number of words: %d\n", words);

 

    return 0;

}

Output

 
OUTPUT :
Enter a string: C programming is powerful
Total number of words: 4

Explanation

  • The program counts words by detecting transitions from spaces (or tabs/newlines) to non-space characters.
  • fgets() safely reads the full line (including spaces).
  • Leading/trailing spaces are handled correctly.