C program to count number of words in a string

Write a C program to count total number of words in a string using loop. How to find total number of words in a given string using loops in C programming. Logic to count total number of words in a string.

Example

Input

Input string: I love Codeforwin.

Output

Total number of words: 4

Required knowledge

Basic C programming, If else, For loop, String

Logic to count number of words in a string

To count total number of words in a string we just need to count total number of white spaces. White space characters includes single blank space ‘ ‘, Tab \t, New line \n.

Algorithm to find total number of words in a string
%%Input : text {Array of characters /String}
        N {Size of the string}
Begin:
    words ← 0;
    For i ← 0 to N do
        If (text [i] == ' ', 't', 'n') then
            wordword + 1;
        End if
    End for
End

Program to count number of words in string

/**
 * C program to count total number of words in a string
 */

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size

int main()
{
    char str[MAX_SIZE];
    int i, words;

    /* Input string from user */
    printf("Enter any string: ");
    gets(str);

    i = 0;
    words = 1;

    /* Runs a loop till end of string */
    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;
}

That was an easy drill. The above method to count number of words is simplest to understand and implement. However, it’s not the optimal method. In the above program we left many conditions, that leads to falsy algorithm. Let us see cases we missed –

  1. Run the program and hit enter key without entering any other character. The program prints 1, which shouldn’t as there are no words.
  2. Run it again and feed in more than one spaces between two words. Again it gives wrong output. As it is designed to count every white space character as a word.

Google says word is a single distinct meaningful element of speech or writing, used with others (or sometimes alone) to form a sentence and typically shown with a space on either side when written or printed. Therefore, we need to make little changes in our algorithm. If a non-white space character is followed by a white space or NULL character then it is a word. Let us implement this new logic to our program.

/**
 * C program to count total number of words in a string
 */

#include <stdio.h>

#define MAX_SIZE 100 // Maximum string size

int main()
{
    char str[MAX_SIZE];
    char prevChar;
    int i, words;

    /* Input string from user */
    printf("Enter any string: ");
    gets(str);

    i = 0;
    words = 0;
    prevChar = '\0'; // The previous character of str[0] is null

    /* Runs loop infinite times */
    while(1)
    {
        if(str[i]==' ' || str[i]=='\n' || str[i]=='\t' || str[i]=='\0')
        {
            /**
             * It is a word if current character is whitespace and
             * previous character is non-white space.
             */
            if(prevChar != ' ' && prevChar != '\n' && prevChar != '\t' && prevChar != '\0')
            {
                words++;
            }
        }

        /* Make the current character as previous character */
        prevChar = str[i];

        if(str[i] == '\0')
             break;
        else
             i++;
    }

    printf("Total number of words = %d", words);

    return 0;
}

Output

Enter any string: I love C    programming and Codeforwin!
Total number of words = 6

Happy coding 😉