计算2D char数组中单词的出现次数

时间:2014-10-19 00:58:48

标签: c arrays string loops char

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

我有一个名为words

的2D字符数组

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

words中的字总数称为totalWords

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

我已为words填写了以下内容:

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]);

}

1 个答案:

答案 0 :(得分:1)

您可以使用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);

您可能还需要考虑使用struct数组,您的struct具有字符串类型和存储no的int。匹配,用于在该循环中更系统地存储输出。