How to count words in a string

Programming

About

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.


Example

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.


Example

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(){
	//variables
	char str[200];
	int w = 0, i = 0;

	//input
	printf("Enter your sentence:\n");
	gets(str);

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

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

Note!
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.