I need to write a function that will count words in a string. For the purpose of this assignment, a "word" is defined to be a sequence of non-null, non-whitespace characters, separated from other words by whitespace.
This is what I have so far:
int words(const char sentence[]);
int i, length = 0, count = 0, last = 0;
length = strlen(sentence);
for (i = 0, i < length, i++)
if (sentence[i] != ' ')
if (last=0)
count++;
else
last = 1;
else
last = 0;
return count;
I am not sure if it works or not because I can't test it until my whole program is finished and I am not sure it will work, is there a better way of writing this function?
strtok
, as separating things is what it's meant to do. Anyway,if (sentence[i] >= '!' && sentence[i] >= '~')
has something a bit incorrect beyond just relying on ASCII to be used. – Smelser!
and~
? Everything what's not whitespace is part of a word. – Sorites