简体   繁体   中英

Mapping enum and string

I have an array say arr[3] and I used enums to index into the array say

typedef enum {
ABC,
DEF,
XYZ
}INDEX;

I store values in the array as ar[ABC] = 100 and so on... Now I have a file having the strings as xyZ = 2, dEF = 3, abc = 4 . I parse this file and check for the string. If the string is xyZ then I need to store the value in the array arr[XYZ] and so on.. I am struck in mapping the string with enums.How will I know the enum index with the strings in file. Any ideas please. Hope I am clear.Thanks

You can take 'a' as index 0

#include <stdio.h>

typedef enum {
    ABC,
    DEF,
    GHI,
    JKL,
    MNO,
    PQR,
    STU,
    VWX,
    YZ,
    N
} INDEX;

#define GET_INDEX(x) (((x) - 'a') / 3)

int main(void)
{
    char *s[] = {"abc", "def", "mno", "def"};
    int i, arr[N] = {0};

    for (i = 0; i < 4; i++) {
        arr[GET_INDEX(s[i][0])] += 1;
    }
    for (i = 0; i < N; i++) {
        printf("arr[%d]=%d\n", i, arr[i]);
    }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM