首页 > 解决方案 > 如何计算单词出现在短语中的次数

问题描述

我正在尝试创建一个代码,其中我必须计算一个单词在句子中出现的次数,但是经过大量搜索和搜索,我只能找到使用该fgets函数的代码,我想知道是否你会知道其他什么东西,我可以替换fgets并仍然工作整个事情。

这是我现在开发的代码:

#include <stdio.h>

int
main()
{
    char phrase[250];
    char word[50], c;
    int count;
    int a;

    count = 0;

    printf("Type a phrase: ");
    scanf("%[^\n]", &phrase);
    printf("Type a word: ");
    scanf("%s", &word);

    for (a = 0; word[a] != '\0'; a++) {
        if (word[a] == c)
            count++;

    }

    if (count == 0) {
        printf("word not found in the sentence");
    }
    else {
        printf("Count: = %d\n", count);
    }

    return 0;
}

除了一切,我相信我在 for 中做错了什么,但我无法理解。如果你能帮助我理解我的错误,以及除了可以使用的其他东西fgets,我很乐意。

标签: cfunction

解决方案


我不明白你的for循环和if陈述。我没有测试这段代码。但它的逻辑可能会有所帮助:

int j = 0;
int counter = 0;
for(int i = 0; phrase[i] != '\0'; i++)
{
    if (word[j] = phrase[i])
    {
        j += 1;
        if (word[j] == '\0')
        {
            counter += 1;
            j = 0;
        }
    }
    else
    {
        j = 0;
    }
    
}

推荐阅读