Just so you know, this isn't a homework problem. I'm trying to practice by writing more programs on my own. So, I have to write a program that counts the number of words in a string. I've used the relationship between the number of spaces and the number of words in a sentence for my program. (the number of words seems to be one more than the number of spaces in a sentence). But, when I tried testing it, the compiler said that the string "Apple juice" only had 1 word. :( I'm not sure why my code could be wrong.
Here's my code:
int words_in_string(char str[])
{
int spaces = 0, num_words;
for (int i = 0; i != '\0'; i++)
{
if (str[i] == ' ')
{
spaces = spaces + 1;
}
}
num_words = spaces + 1;
return num_words;
}
int words_in_string(char str[])
{
int spaces = 0, num_words;
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] == ' ')
{
spaces = spaces + 1;
}
}
num_words = spaces + 1;
return num_words;
}
The stop condition should be
str[i] != '\0'
You got the code correct but assuming number of words is 1 greater than number of spaces is a faulty assumption. You can have a sentence to begin with space or end with space or both. Your logic will fail in that case.
int words_in_string(const char *str){
int in_word = 0, num_words = 0;
while(*str){
if(isspace(*str++))
in_word = 0;
else{
if(in_word == 0) ++num_words;
in_word = 1;
}
}
return num_words;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.