如何使用c查找字符串中的项目数?

时间:2019-06-11 15:59:03

标签: c

传递字符串S作为输入。该程序必须打印S中的文章数。

我不知道这个问题。帮助我找到解决此问题的方法。

输入: 昨天我和一个老人一起去看电影。

输出: 2

字符串中有两篇文章。

1 个答案:

答案 0 :(得分:0)

我不确定您的问题在哪里,所以我希望这可以为您提供帮助

您可以输入文本女巫scanf。要拆分此字符串,请使用strtok和用于比较器strcmp。 还要看: https://devdocs.io/c/string/byte/strtok

https://devdocs.io/c/string/byte/strcmp

所以这是它的样子:

int main()
{

    char arr[MAX];
    printf("Input: ");
    scanf("%[^\n]s",arr);
    int count = 0;
    char *token = strtok(arr, " ");
    while(token)
    {
        if(strcmp(token, "an") == 0|| strcmp(token, "a") == 0 || strcmp(token, "the") == 0)
            count++;
        if(strcmp(token, "An") == 0|| strcmp(token, "A") == 0 || strcmp(token, "The") == 0)
            count++;
        token = strtok(NULL, " ");
    }
    printf("Output: %d", count);
    return 0;
}

您可以为文章创建一个char数组,然后进行插入。而且不要怀疑要为此提供图书馆;)