[英]Mapping enum and string
I have an array say arr[3]
and I used enums to index into the array say 我有一个数组说
arr[3]
,我用枚举索引到数组说
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
. 我在数组中将值存储为
ar[ABC] = 100
,依此类推...现在我有一个文件,其字符串为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. 如果字符串是
xyZ
那么我需要将值存储在数组arr[XYZ]
,依此类推。.在使用enums映射字符串时,我感到很震惊。我怎么知道文件中包含字符串的enum索引。 Any ideas please. 有什么想法。 Hope I am clear.Thanks
希望我清楚。谢谢
You can take 'a'
as index 0
您可以将
'a'
作为索引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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.