就在C字符串转换最好的方法 [英] best way to switch on a string in C

查看:149
本文介绍了就在C字符串转换最好的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中有一个开关结构,这使得人们能够执行基于一个测试整数值code,例如不同的条件分支:

In C there is a switch construct, which enables one to execute different conditional branches of code based on an test integer value, e.g.:

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;
}

这怎么可能获得相同的行为(即避免了所谓的如果 - 其他梯)为一个字符串值,即的char *

How is it possible to obtain the same behavior (i.e. avoid the so-called "if-else ladder") for a string value, i.e. a char *?

推荐答案

如果你的意思是,怎么写类似这样的东西:

If you mean, how to write something similar to this:

// switch statement
switch (string) {
  case "B1": 
    // do something
    break;
  /* more case "xxx" parts */
}

然后在C典型的解决方案是使用的if-else梯:

Then the canonical solution in C is to use an if-else ladder:

if (strcmp(string, "B1") == 0) 
{
  // do something
} 
else if (strcmp(string, "xxx") == 0)
{
  // do something else
}
/* more else if clauses */
else /* default: */
{
}

这篇关于就在C字符串转换最好的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆