Write a function called nbrofWords that has an array of characters as parameter (string). This function must return the number of words in this string without considering spaces. We suppose that the string is composed of words separated by single blank space.
Test this function in the main function.
Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>
int nbrofWords(char str[])
{
int i , c=0;
for(i=1;str[i];i++)
if(str[i]==' ' && str[i-1]!=' ')
c++;
if(str[i-1]!=' ') c++;
return c;
}
int main()
{
char str1[]=" a bc defg ", str2[]=" a bc defg h";
printf("Nb of words in str1 = %d\n",nbrofWords(str1));
printf("Nb of words in str2 = %d\n",nbrofWords(str2));
return 0;
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Sorting distinct elements of a queue