简体   繁体   English

为什么我的程序无法计算字符串中的单词?

[英]Why does my program not work for counting the words in a string?

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. 但是,当我尝试对其进行测试时,编译器说字符串“ Apple juice”只有1个字。 :( 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. 您的代码正确无误,但是假设单词数比空格数大1。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM