Assuming that you don't have words that contain alphanumeric combinations, like "foo12", then you could combine your code snippets, like this:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[] = "Bex 67 rep";
int len = strlen(str);
int count = 0, i = 0;
while(str[i] != '\0')
{
if(str[i] == ' ')
{
if(i + 1 < len && ! (str[i + 1] >= '0' && str[i + 1] <= '9') && str[i + 1] != ' ')
count++;
}
i++;
}
printf("Word count = %d\n", count + 1); // Word count = 2
return 0;
}
where you loop over every character of the string, and when you find a whitespace, you check - if you are not at the last character of the string - if the next character is not a digit or a whitespace. If that's the case, then you can assume that the whitespace you encountered is precedended of a word, thus incease count
.
Notice however that usually senteces do not start with a whitespace (which is an extra assumption for this answer), thus the number of words is one more than count
.
In real life, use strtok()
and check every token for its validity, since that's approach is just for demonstration and should be considered a bad approach.