C program to count words in a string – handle spaces

C program to count words in a string with simple logic. This program will handle all spaces in the given string. Also, it counts special characters as a word if any. For example,

Input:  Hello world
Output: Number of words: 2
Input: Hello world !!!
Number of words: 3

Count words C program example


#include<stdio.h>

//C program to count number of words
//in a string
int countWords(const char *s){

	int wordCount=0;
	int len = 0;

	//If string is null or empty then
	//return 0;
	if(!s || !*s)
		return 0;

	//traverse the string
	while(*s){

		//As soon as find space
		//in string the reset
		//the len
		if(*s == ' ')
		{
			len = 0;
		}else if(++len == 1)
		{
			//if only len is equl to 1
			//then increment the count
			++wordCount;
		}

		++s;
	}

	return wordCount;
}

int main(){

	int count = 0;
	char str[100];	
	printf("Enter String: ");

	//Read the entire string with spaces	
	//in str variable declared
	gets(str);

	//call count words function
	count = countWords(str);
	printf("Number of words: %d",count);

	return 0;
}


Related Posts