翻译数组

时间:2017-01-18 02:40:16

标签: c arrays string

我需要做一个简单的翻译。例如:

  • 输入:“foo”输出:“bar”
  • 输入:“the”输出:“teh”
  • 输入:“what”输出:“wut”

我知道我可以这样写:

if (!strcmp(input, "foo"))
    puts("bar");
else if (!strcmp(input, "the"))
    puts("teh");
else if (!strcmp(input, "what"))
    puts("wut");

但这很大而且很混乱。有这样做的捷径吗?我知道在PHP中(抱歉不可避免的语法错误,我不精通)有类似的东西:

value = array(
    "foo" => "bar",
    "the" => "teh",
    "what" => "wut"
);

如何使用类似PHP数组的东西缩短原始代码?

3 个答案:

答案 0 :(得分:5)

您可以定义struct,其中包含单词和翻译:

typedef struct {
    const char *word;
    const char *translation;
} translate_t;

然后你可以像这样创建一个结构数组:

const translate_t translate[] = {{"foo", "bar"},
                                 {"the", "teh"},
                                 {"what", "wut"}};

如果您想打印出单词和翻译,那么您可以这样做:

size_t size = sizeof translate/sizeof *translate;

for (size_t i = 0; i < size; i++) {
    printf("Word: %s Translation: %s\n", translate[i].word, translate[i].translation);
}

将输出:

Word: foo Translation: bar
Word: the Translation: teh
Word: what Translation: wut

这是将单词与翻译相关联的好方法。

UPDATE :@Olaf建议使用size的宏,这对于声明数组的大小要好得多。因此,上面的代码可以表示为:

#define ARRAY_SIZE(x) ((sizeof x)/sizeof *x) /* near top, or before main() is a good place for this */

for (size_t i = 0; ARRAY_SIZE(translate); i++) {
    printf("Word: %s Translation: %s\n", translate[i].word, translate[i].translation);
}

答案 1 :(得分:0)

找到它:

const char *Translate[] = {
    "foo",  "bar",
    "the",  "teh",
    "what", "wut"
};

int t_idx(char *s)
{
    int i;
    for (i = 0; Translate[i]; i += 2)
        if (!strcmp(Translate[i], s))
            return i+1;

    return -1;
}

const char *translate(char *s)
{
    int idx = t_idx(s);

    return (idx == -1) ? s : Translate[idx];
}

返回translate的值:

translate("what") = "wut"
translate("some") = "some"
translate("foo")  = "bar"

答案 2 :(得分:0)

标准C中没有map或关联数组类型;你必须自己实现它。一个简单的想法是使用struct

#include <string.h>
#include <stdio.h>

struct map {
  struct map_elem {
    char *key;
    char *value;
  } * elem;
  size_t size;
};

int main(void) {
  struct map_elem map_elem[] = {
      {"foo", "bar"}, {"the", "teh"}, {"what", "wut"}};

  struct map const map = {map_elem, sizeof map_elem / sizeof *map_elem};

  char input[] = "foo";

  for (size_t i = 0; i < map.size; i++) {
    struct map_elem *elem = map.elem + i;
    if (strcmp(input, elem->key) == 0) {
      puts(elem->value);
      break;
    }
  }
}

当然,这只是一个小例子。