可以字符串被用来作为数组索引? [英] Can strings be used as an array index?

查看:609
本文介绍了可以字符串被用来作为数组索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否在字符串中使用在C数组索引?

Can a string be used as array index in C?

例如:
字符串对应的值
一1
两节2
十二五5
TEN10

Ex: String Corresponding value "ONE" 1 "TWO" 2 "FIVE" 5 "TEN" 10

当在上述列表中的字符串被传递给函数,该函数必须返回上述的相应的值。这可以通过声明一个常量数组与字符串作为指标来实现。

When a string in the above list is passed to the function, the function must return the corresponding value indicated above. Can this be achieved by declaring a constant array with string as index

int *x;
x["ONE"]  = 1;
x["TWO"]  = 2;
x["FIVE"] = 5;
x["TEN"]  = 5;

return x["string received by the function"];

如预期上述逻辑不工作;有没有实施上述逻辑,为了有一个字符串数组索引?一个解决办法

The above logic does not work as expected; is there a workaround to implement the above logic in order to have a string-indexed array?

推荐答案

这可能编译,但它不会工作。

It might compile, but it won't work.

这不是完全清楚你想达到的目标。我想你想的关联数组,在这种情况下,你应该找一个库实现之一。

It's not entirely clear what you're trying to achieve. I think you want an associative array, in which case you should find a library implementation of one.

如果您正在寻找的东西更像是一个枚举类型,你可以依靠的C89 ,看是这样的:

If you're looking for something more like an enumerated type, and you can rely on C89, look at something like:

enum cardsuit {
   CLUBS,
   DIAMONDS,
   HEARTS,
   SPADES
};

如果您不能依靠C89,那么你应该尝试一些的typedef 挂羊头卖狗肉。

If you can't rely on C89, then you should try some typedef trickery.

这篇关于可以字符串被用来作为数组索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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