gpt4 book ai didi

计算相同和重复单词的数量

转载 作者:太空宇宙 更新时间:2023-11-03 23:29:34 25 4
gpt4 key购买 nike

我的代码计算给定字符串上的关键字数量,但我需要将重复的关键字计为 1,并将其计为唯一关键字。有人可以帮我吗,我不知道该怎么做 :( .请问?

#include <stdio.h>
#include <string.h>

int main()
{
char string[] = "\nauto else else do while >> \nfor 1+2 == goto";
char *keywords[] =
{ "auto", "break", "else", "case", "if" };
int s = 0, i, x = 1;
char *result;
char delims[] = " \n";
int keyword = 0, ukeyword = 0;

printf("Input: %s", string);
//Count the number of lines
for (i = 0; string[i] != '\0'; ++i)
{
if (string[i] == '\n')
++s;
}
printf("\n\nNo. of lines: %d", s);

result = strtok(string, delims);
while (result != NULL )
{
for (x = 0; x != 5; x++)
{
if (strcmp(result, keywords[x]) == 0)
{
keyword++;
}
}

result = strtok(NULL, delims);
}

printf("\nNo. of keywords: %d.\n", keyword);
printf("\nNo. of unique keywords: %d.\n", ukeyword);
return 0;
}

所以输出应该是:

Input:
auto else else do while >>
for 1+2 == goto

No. of lines:2
No. of keywords:3
No. of unique keywords:2

最佳答案

您必须分别计算每个关键字的出现次数:

int keyword_count[5];

并且当您找到关键字时,您必须增加相应的计数器:

keywords ++;
keyword_count[x] ++;

最后唯一关键字是那些具有 keyword_count[x]==1 的关键字

关于计算相同和重复单词的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19069420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com