C program that count number of words in a string using pointers

      Strings in C programming are terminated with special character i.e., is ‘\0 ‘. This program counts the number of words in a given string by scanning the every character of a
input string from start to end and checking whether it is space or not. So whenever it encounters a space it will consider the characters it scanned as one word. This way when it reaches the end of the string (i.e., ‘\0’) it will count number of words in a string. The space in a given string is checked using isspace() function available in “ctype.h”.

count number of words in a string



Source Code :

#include<stdio.h>
#include<ctype.h>
int word_cnt(char *s)
{
   int cnt = 0;
   while( *s != '\0')
    {                                              
       while(isspace(*s))  // Step 3 
       ++ s ;                                  
       if(*s != '\0')
       {		 //Step 4
	 ++ cnt;          
	 while(!isspace(*s) && *s != '\0') //Step 5
	 ++ s;
	}
     }
   return cnt;
}
int main()
{
    char str [80];
    printf("\n ENTER THE SENTENCE");   
    scanf("%[^\n]", str);    //Step 1
    printf("\n NO OF WORDS =% d", word_cnt(str));  //Step 6
    return 0;
}


edit-code-image

Sample Test cases:

1.  ENTER THE SENTENCE : topoint is good source of programming questions
    NO OF WORDS = 7

2.  ENTER THE SENTENCE : this is topoint
    NO OF WORDS = 3

Explanation:

Step 1: The program reads a string from the user using scanf() function. The flex(^) operator combined with ‘\n’ helps to read a string until ‘\n’ occurs in the input.

Step 2: The function word_cnt(str) is called from the main program.

Step 3: This while loop helps to remove spaces before the occurance of word.

Step 4: The count is incremented because the while loop encounters the word.

Step 5: This step helps to move to the end of single word that currently while loop encounters.

Step 6: The word count that is returned from the function is printed on the output screen using printf() function.

More Content : C Programs
More about C Programming : C Programming