问题
I have 6 const strings (5 letters each)
I get a stream of few words (out of these 6 words).
I want to count how many occurrences were out of each word.
How can I implement it in C ?
I have tried:
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)
{
...
}
..
}
for example for this stream:
"wooo_","wooo_","faceb","wooo_","google"
I will eventually get:
"wooo_" 3 times
"faceb" 1 times
"google" 1 times
"fours" 0 times
"fuelil" 0 times
"yello" 0 times
回答1:
I use 2 arrays instead of 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) {
...
}
}
}
}
}
来源:https://stackoverflow.com/questions/17522342/how-to-implement-counting-hashmap-in-c