Write the function NWORDS which returns as result the number of words contained in a string of characters.

Use a logical variable, the function isspace and a helper variable N.


Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>
#include <ctype.h>

int NWORDS(char str[])
{
	int i = 0;
	int N;        /* number of words */
	int In_a_word; /* logival variable : */
				  /* true if str points inside a word */
	In_a_word = 0;
	N = 0;
	for (; str[i]; i++)
		if (isspace(str[i]))
			In_a_word = 0;
		else if (!In_a_word)
		{
			In_a_word = 1;
			N++;
		}
	return N;
}

void main()
{
	char str[100];
	printf("Enter a string: ");
	gets(str);
	printf("Number of words = %d\n", NWORDS(str));

	getch();
}

 

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Replace all occurrences of a string in an another string