I have an enum Eg.
enum {
APPLE,
MANGO,
BANANA
}
and a corresponding string array
char fruits[] = 
{
 "apple",
 "mango",
 "banana"
}
I need to retrieve the index of string, given I have the string. So given that the string is apple, I need to get 0 and so on. [ Enum is additionally there, might help the solution]
Is there an elegant way, to save [apple,0],[banana,1] that is short and simple, that I might use as a macro. I don't need lengthy things like a hashtable. Can Enum assist in the mapping?
You can do something like
entries.h
 ENTRY(APPLE, "apple"), 
 ENTRY(MANGO, "mango"),
In your file
#define ENTRY(a,b) b
const char *fruits [] = {
#include "entries.h"
} ; 
#undef ENTRY
#define ENTRY(a,b) a
enum fruit_t
{
#include "entries.h"
} ;
                        You can't really do a "mapping" with strings in C.
The most straightforward solution is a simple linear search:
typedef enum {
  INVALID = -1,
  APPLE = 0,
  MANGO,
  BANANA,
  NUM_FRUIT,
} fruit_t;
// NOTE: These indices must be kept in-sync with fruit_t!
const char* fruits[] = {
 "apple",
 "mango",
 "banana"
};
fruit_t lookup_fruit(const char* name) {
    int i;
    for (i=0; i<NUM_FRUIT; i++) {
        if (strcmp(name, fruits[i]) == 0)
            return i;
    }
    return INVALID;
}
void test(void) {
    fruit_t result = lookup_fruit("mango");
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With