C code to count the number of words in a string | LeetCode
Count the number of words in a string, where a word is defined to be a contiguous sequence of non-space characters.
eg, “Hello, my name is John.” -> 5
Take account for extra spaces at the start and end of the string, and there might be more than multiple spaces between words.
The key is to note when it is in a word and when it is not; When it changes from not-in-word to in-word, increment wordCount by one.
Count the number of words in a string, where a word is defined to be a contiguous sequence of non-space characters.
eg, “Hello, my name is John.” -> 5
Take account for extra spaces at the start and end of the string, and there might be more than multiple spaces between words.
The key is to note when it is in a word and when it is not; When it changes from not-in-word to in-word, increment wordCount by one.
int countNumWords(const char *str) {
bool inWord = false;
int wordCount = 0;
while (*str) {
if (!inWord && isalpha(*str)) {
inWord = true;
wordCount++;
}
else if (inWord && *str == ' ') {
inWord = false;
}
str++;
}
return wordCount;
}
Read full article from C code to count the number of words in a string | LeetCode