如何使用`switch`语句比较C中的字符串? [英] How can I compare strings in C using a `switch` statement?

查看:128
本文介绍了如何使用`switch`语句比较C中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中,有一个 switch 构造,该构造使一个人可以基于测试整数值(例如,

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

对于字符串值(即<代码>字符* ?

推荐答案

如果您的意思是,如何编写与此类似的内容:

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: */
{
}

这篇关于如何使用`switch`语句比较C中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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