How to count words in a string




If the sentence entered has one space between every two words and if there are n spaces in the sentence then there are n+1 words.


Have a nice day.

There are 3 spaces so we have 4 words.

But if the words have more than one space between them then we have to count the words and not the spaces.


Have     a         nice      day.

There are 20 spaces but only 4 words.

How to solve

We will use variable w to count number of words

Initially set w = 0

Scan the string from left to right

If a word is encountered increment w by 1
And go to the end of that word

After scanning is complete
Print: No. of words = w

Code in C

#include <stdio.h>

int main(){
	char str[200];
	int w = 0, i = 0;

	printf("Enter your sentence:\n");

	//count words
	for(i = 0; str[i] != '\0'; i++){
		if(str[i] != ' ' && str[i] != '\t'){
			while(str[i] != ' ' && str[i] != '\t')

	printf("No. of words = %d\n", w);
	return 0;

This is just one way of counting words. You are encouraged to experiment with the logic and write a different/better version of the code.