Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain a mapping between a string and it's index in C? [duplicate]

Tags:

c

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?

like image 394
Hooli Avatar asked Dec 05 '22 06:12

Hooli


2 Answers

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"
} ;
like image 96
user3344003 Avatar answered May 29 '23 20:05

user3344003


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");
}
like image 26
Jonathon Reinhart Avatar answered May 29 '23 22:05

Jonathon Reinhart