switch 语句中的 C 字符串 [英] C strings in a switch statement

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

问题描述

可能的重复:
在 C 中打开字符串的最佳方法

用于字符串(c 字符数组)和 switch 语句的一般方法是什么?我正在查询我的数据库中存储为

What is the general approach that is being used for strings (c character arrays) together with a switch statement? I'm querying my database for currencies that are stored as

"USD"
"EUR"
"GBP"

等等.来自 PHP 背景,我会简单地做:

and so on. Coming from a PHP background, I would simply do:

switch ($string) {
  case "USD":
   return "$";
   break;
  case "EUR":
   return "€";
   break;   
  case "GBP":
   return "£";
   break;
  default:
   return "$";
}

在 C 中,case-value 必须是一个整数.我将如何在 C 中实现类似的东西?我最终会在一个巨大的 if/else 块中编写大量 strcmp 吗?另请注意,我不能简单地比较货币的第一个字符,因为有些(尽管在此示例中不是)以相同的字符开头.

In C the case-value has to be an integer. How would I go about implementing something like that in C? Will I end up writing lots of strcmp's in a huge if/else block? Please also note that I cannot simply compare the first characters of the currencies as some (not in this example though) start with the same character.

推荐答案

一种方法是定义一个 C 字符串数组,并将其用作排序的定义:

One way would be defining an array of C strings, and use it as a definition of your ordering:

const char *currencies[] = {"USD", "GBP", "EUR"};

现在您可以在 currencies 中搜索您的字符串,并在 switch 语句中使用它的 index.

Now you can search currencies for your string, and use its index in a switch statement.

你可以花哨和排序你的字符串,并使用 bsearch 找到O(LogN)

You can get fancy and - sort your strings, and use bsearch to find the index in O(LogN)

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

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