如何在c中实现计数hashmap?

时间:2013-07-08 08:45:10

标签: c string hashmap

我有6个常量字符串(每个5个字母)

我得到了几个单词的流(在这6个单词中)。

我想计算每个单词的出现次数。

如何在C中实现它?

我试过了:

  char searchEngineNames[6][5] = { "waze_", "faceb", "fours", "googl",
        "fueli", "yello" };

    static void foo(const char* res_name, int success, void *context, char *last_modified) {
        if (success){
                for (int i=0; i<6; i++)
                {
                    char substringFiveChars[6];

                    strncpy(substringFiveChars, res_name, 5);

                            char substringFiveChars[6]; 

                            substringFiveChars[5] = 0;

                    if (strcmp(searchEngineNames[i],substringFiveChars) == 0)
                    {
                    ... 
                    }
    ..
                }

例如此流:

  

“的Wooo _”, “的Wooo _”, “faceb”, “的Wooo _”, “谷歌”

我最终会得到:

  

"wooo_" 3 times

"faceb" 1 times 

"google" 1 times 

"fours" 0 times

"fuelil" 0 times

"yello" 0 times

1 个答案:

答案 0 :(得分:0)

我使用2个数组而不是1个。

char searchEngineNames[6][5] = { "wooo_", "faceb", "fours", "google",
        "fuelil", "yello" };

int searchEngineCounts[6] = {0,0,0,0,0,0};



static void foo(const char* res_name,
        int success, void *context, char *last_modified) {
    if (success) {

        int i = 0;
        for (i; i < 6; i++) {
            char substringFiveChars[6];

            strncpy(substringFiveChars, res_name+7, 5);

            substringFiveChars[5] = 0;

            if (strcmp(searchEngineNames[i], substringFiveChars) == 0) {
                searchEngineCounts[i]++;

                if (searchEngineCounts[i] < 3) {

...
                }
            }
        }

    }
}