gpt4 book ai didi

计算二维字符数组中单词的出现次数

转载 作者:行者123 更新时间:2023-11-30 15:28:49 25 4
gpt4 key购买 nike

我正在尝试计算数组中每个单词的出现次数并将其存储。我还想要最常出现的单词的索引

我有一个名为 words 的 2D 字符数组

存储出现次数的整数数组称为count

words 中的单词总数称为 totalWords

到目前为止,我已完成以下操作:

我已用以下内容填充单词:

strcpy(words[0], "Me");
strcpy(words[1], "You");
strcpy(words[2], "Me");
strcpy(words[3], "They");


for (i = 0; i < totalWords; i++){

count[i] = //need help here

printf("%d times\n ", count[i]);

}

最佳答案

您可以使用 strcmp() 来比较循环中的字符串,例如 for 循环。如果单词匹配,则增加计数器。

char *words[] = {
"Me",
"You",
"Me",
"They",
};
int i;
int j;
int counter = 0;
int temp = 0;

char *longest = NULL;

//loop to compare the words in your array of strings to
//other words in the array
for(i = 0; i < 4; i++) {
for(j = i + 1; j < 4; j++) {
if(strcmp(*(words + i), *(words + j)) == 0) {
temp++;
}
}
if (temp > counter) {
counter = temp;
longest = *(words + i);
}
temp = 0;
}

printf("For word \"%s\": %d match\n", longest,counter);

您可能还需要考虑拥有一个结构数组,其中您的结构具有字符串类型和存储编号的 int。匹配,以便更系统地存储该循环中的输出。

关于计算二维字符数组中单词的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26446176/

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