我有一组确定的字符串及其对应的数字:
kill -> 1
live -> 2
half_kill -> 3
dont_live -> 4
List 是 30 个这样的字符串及其编号映射。
如果用户输入“kill”,我需要返回 1,如果他输入“dont_live”,我需要返回 4。
我应该如何在 C 程序中实现这一点?我正在寻找一种有效的解决方案,因为此操作需要执行 100 次。
- 我应该将它们放在我的 .h 文件中的#define 中吗?
提前致谢。
最佳答案
对表格进行排序,并使用标准库函数bsearch执行二进制搜索。
#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;
}
这是您运行该程序时得到的结果。
$ ./a.out kill
1
$ ./a.out half_kill
3
$ ./a.out foo
<no output>
PS:我重复使用了 sidyll 程序的部分内容。我的答案现在应该符合 CC BY-SA :p
关于c - 如何在 C 程序中最好地实现字符串到数字的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6669842/