Reputation: 1208
I have a JSON parser that sends a callback for every parsed key-value pair. I then use strncmp
with statically allocated strings in my program to check if the field matches any of the fields I am interested in. I have now ended up with a dozen of strncmp
in if-else
statements:
if (strncmp(input, "apple", sizeof("apple")-1) == 0)
{// do something}
else if (strncmp(input, "banana", sizeof("banana")-1) == 0)
{// do something}
I'm not sure if this is an optimal/maintainable way of getting the job done. Is there a better way to do it? I already precompute the string lengths at compile time.
Upvotes: -1
Views: 80
Reputation: 661
You could define an array of static strings:
const char *field_names[] = {
"apple",
"banana",
NULL
};
And then loop over the array, looking if the string matches one on the elements of the array:
for (int i = 0; field_names[i] != NULL; i++) {
if (!strcmp(input, field_names[i]))
// Do things
}
If you need to limit the size of the comparison, you could have an array a structures combining the name string + the size.
And if you need to do a different action for each one, you could include a function pointer in the structure to indicate what to do.
Upvotes: 1
Reputation: 11950
Depends on the size of your set. For large amount of long patterns, your O(MN) lookup is surely not optimal.
You can store them in a hash set (O(M) on average), or in a trie. You can even hardcode one on your own, if you've got a really fixed set of patterns from the Delphic Oracle and first letters are distributed more or less uniformly among patterns:
switch(input[0]) {
case 'a': // check that it's an "apple"
break;
}
Upvotes: 0