0

只是让你知道,这不是一个家庭作业问题。我正在尝试通过自己编写更多程序来练习。所以,我必须编写一个程序来计算字符串中的单词数。我在我的程序中使用了一个句子中空格数和单词数之间的关系。(单词的数量似乎比句子中的空格数多一)。但是,当我尝试测试它时,编译器说字符串“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;
}
4

3 回答 3

6
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'
于 2013-05-30T04:51:21.570 回答
0
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;
}
于 2013-05-30T08:33:05.387 回答
0

您得到了正确的代码,但假设字数比空格数大 1 是错误的假设。您可以让句子以空格开头或以空格结尾或两者兼而有之。在这种情况下,您的逻辑将失败。

于 2013-05-30T05:29:19.557 回答