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.

Example:
Input string: I love C programming!
Total number of words: 4

Required knowledge

Basic C programming, If else, For loop, String

Logic to count number of words

To count total number of words in a string we just need to count total number of white spaces which 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 size of the string

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

    /* Reads a string from user */
    printf("Enter any string: ");
    gets(string);

    i = 0;
    words = 1;

    /* Runs a loop till end of string */
    while(string[i]!='\0')
    {
        /* If the current character(string[i]) is white space */
        if(string[i]==' ' || string[i]=='\n' || string[i]=='\t')
        {
            words++;
        }

        i++;
    }

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

    return 0;
} 


That was an easy drill. The above method to count number of words is simplest to understand and implement. But 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 size of the string

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

    /* Reads a string from user */
    printf("Enter any string: ");
    gets(string);

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

    /* Runs loop infinite times */
    while(1)
    {
        if(string[i]==' ' || string[i]=='\n' || string[i]=='\t' || string[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 = string[i];

        /*
         * If current character is null then terminate else move to next character
         */
        if(string[i]=='\0')
        {
            break;
        }
        else
        {
            i++;
        }
    }

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

    return 0;
}


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

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment