Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to best achieve string to number mapping in a c program

Tags:

performance

c

I have a definite set of strings and its corresponding numbers:

kill -> 1
live -> 2
half_kill -> 3
dont_live -> 4

List is of 30 such strings and their number mapping.

If user enters "kill", I need to return 1 and if he enters "dont_live" I need to return 4.

How should I achieve this in c program? I am looking for an efficient solution because this operation needs to be done 100s of times.

  • should I put them in #define in my .h file?

Thanks in advance.

like image 245
hari Avatar asked Jul 12 '11 19:07

hari


2 Answers

Sort your table, and use the standard library function bsearch to perform a binary search.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct entry {
    char *str;
    int n;
};

/* sorted according to str */
struct entry dict[] = {
    "dont_live", 4,
    "half_kill", 3,
    "kill", 1,
    "live", 2,
};

int compare(const void *s1, const void *s2)
{
     const struct entry *e1 = s1;
     const struct entry *e2 = s2;

     return strcmp(e1->str, e2->str);
}

int
main (int argc, char *argv[])
{
    struct entry *result, key = {argv[1]};

    result = bsearch(&key, dict, sizeof(dict)/sizeof(dict[0]),
                     sizeof dict[0], compare);
    if (result)
        printf("%d\n", result->n);

    return 0;
}

Here's what you get when you run the program.

$ ./a.out kill
1
$ ./a.out half_kill
3
$ ./a.out foo
<no output>

PS: I reused portions of sidyll's program. My answer should now be CC BY-SA compliant :p

like image 81
sigjuice Avatar answered Sep 30 '22 19:09

sigjuice


A possible solution:

#include <stdio.h>
#include <string.h>

struct entry {
    char *str;
    int n;
};

struct entry dict[] = {
    "kill", 1,
    "live", 2,
    "half_kill", 3,
    "dont_live", 4,
    0,0
};

int
number_for_key(char *key)
{
    int i = 0;
    char *name = dict[i].str;
    while (name) {
        if (strcmp(name, key) == 0)
            return dict[i].n;
        name = dict[++i].str;
    }
    return 0;
}

int
main (int argc, char *argv[])
{
    printf("enter your keyword: ");
    char s[100]; scanf("%s", s);
    printf("the number is: %d\n", number_for_key(s));
    return 0;
}
like image 23
sidyll Avatar answered Sep 30 '22 19:09

sidyll