Search code examples
cstringstrncmp

better way for string comparison


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.


Solution

  • 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.