【问题标题】:How to count number of words found in a string in c如何计算在c中的字符串中找到的单词数
【发布时间】:2020-06-03 22:06:08
【问题描述】:

我正在尝试编写一个程序来计算在字符串中找到的单词数,但是我编写的程序会计算空格数。我如何构建这个程序 - 尽可能高效 - 来计算字数?我该怎么说字符串包含 4 个单词和 8 个空格,或者如果它不包含单词而只包含空格?我错过了什么/做错了什么?

#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
string text = get_string("Text: ");
int count_words = 0;
for (int i = 0, n = strlen(text); i < n; i++)
{
    if (isspace (text[i]))
    {
        count_words++;
    }
}
printf("%i\n", count_words + 1);
}

【问题讨论】:

    标签: c cs50


    【解决方案1】:

    检测和计算单词的开头,空格到非空格的转换:

    int count_words = 0;
    bool begin = true;
    for (int i = 0, n = strlen(text); i < n; i++) {
      if (isspace (text[i])) {
        begin = true;
      } else {
        if (begin) count_words++;
        begin = false;
      }
    }
    

    【讨论】:

    • 你能解释一下你做了什么吗?
    【解决方案2】:

    试试这个条件来计算字数:

    if(text[i]!=' ' && text[i+1]==' ')
            Count=count+1;
    

    【讨论】:

    • 如果你不介意解释你做了什么?它有效,但我不明白为什么?
    • 兄弟我已经设置了检查“not a space”和“space after our word”的条件,以便我们可以切出单词。
    • 条件是:检查 i 处是否有“非空格”。然后检查 i 之后是否有空格,如果它是真的,那意味着我们已经切掉了我们的单词。如果您仍然不明白,请告诉我。
    • 只有在您觉得有帮助的情况下,不要忘记将答案标记为正确。
    • 如果输入不包含"Hello"之类的空格,这种方式会报0而不是1。
    猜你喜欢
    • 2020-08-08
    • 1970-01-01
    • 2012-07-07
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 2019-08-27
    相关资源
    最近更新 更多