在C中打开字符串的最佳方法

在C语言中,有一种switch结构,可以使它根据测试整数值执行不同的条件代码分支,例如,


int a;

/* Read the value of "a" from some source, e.g. user input */

switch ( a ) {

case 100:

  // Code

  break;

case 200:

  // Code

  break;

default:

  // Code

  break;

}

对于字符串值(即a),如何获得相同的行为(即避免所谓的“ if- else梯形图”)char *?


莫回无
浏览 436回答 3
3回答

侃侃尔雅

如果您有很多情况,并且不想写大量strcmp()电话,则可以执行以下操作:switch(my_hash_function(the_string)) {    case HASH_B1: ...    /* ...etc... */}您只需要确保您的哈希函数在该字符串的可能值集中没有冲突。

吃鸡游戏

用C语言无法做到这一点。有许多不同的方法。通常,最简单的方法是定义一组代表您的字符串的常量,然后按字符串进行查找以获取常量:#define BADKEY -1#define A1 1#define A2 2#define B1 3#define B2 4typedef struct { char *key; int val; } t_symstruct;static t_symstruct lookuptable[] = {&nbsp; &nbsp; { "A1", A1 }, { "A2", A2 }, { "B1", B1 }, { "B2", B2 }};#define NKEYS (sizeof(lookuptable)/sizeof(t_symstruct))int keyfromstring(char *key){&nbsp; &nbsp; int i;&nbsp; &nbsp; for (i=0; i < NKEYS; i++) {&nbsp; &nbsp; &nbsp; &nbsp; t_symstruct *sym = lookuptable[i];&nbsp; &nbsp; &nbsp; &nbsp; if (strcmp(sym->key, key) == 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return sym->val;&nbsp; &nbsp; }&nbsp; &nbsp; return BADKEY;}/* ... */switch (keyfromstring(somestring)) {case A1: /* ... */ break;case A2: /* ... */ break;case B1: /* ... */ break;case B2: /* ... */ break;case BADKEY: /* handle failed lookup */}当然,有更有效的方法可以做到这一点。如果对键进行排序,则可以使用二进制搜索。您也可以使用哈希表。这些事情以牺牲维护成本为代价来改变您的性能。
打开App,查看更多内容
随时随地看视频慕课网APP