繁体   English   中英

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

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

请注意,这不是作业问题。 我试图通过自己编写更多程序来练习。 因此,我必须编写一个程序来计算字符串中单词的数量。 我在程序中使用了空格数和句子中的单词数之间的关系。 (单词数似乎比句子中的空格数多一)。 但是,当我尝试对其进行测试时,编译器说字符串“ Apple juice”只有1个字。 :(我不确定为什么我的代码可能是错误的。

这是我的代码:

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;
}

停止条件应为

str[i] != '\0'

您的代码正确无误,但是假设单词数比空格数大1。 您可以使用以空格开头或以空格结尾或两者兼有的句子。 在这种情况下,您的逻辑将失败。

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