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

标签 c arrays string loops char

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

我有一个名为 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/

相关文章:

c++ - Python 和 C 语言的服务器和客户端

c - 在 C 语言中使用 If else 处理 Char

c - 在 WINAPI 中指定窗口绘画区域

javascript - 测试 Date 对象的升序 Javascript 数组

ios - 在将项目附加到数组之前从数组中读取(崩溃)

python - 如何创建可用作实际字符串的可变字符串类?

c - 无法在 C 中使用 qsort 对 dirent 进行排序

arrays - 如何将多图表保存为 .png?

c++初学者---使用指针修改字符串

c# - 在 C# 中使用 Newtonsoft.Json.Linq 查询 JSON 操作日期字符串