什么是好的 switch 语句替代方案? [英] What is a good switch statement alternative?

查看:35
本文介绍了什么是好的 switch 语句替代方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串数组,每个字符串包含 3 个字母.每 3 个字母(每个元素)对应一个唯一的字母.我需要从字符串数组创建一个字符数组.

I have a string array containing strings of 3 letters each. Every 3 letters (every element) corresponds to a unique letter. I need to create a char array from the string array.

我能想到的唯一方法是遍历字符串数组中的每个元素,并使用长 switch 语句来确定其关联的单个字符.

The only way i can think of doing this is looping through each element in the array of strings and using a long switch statement to determine its associated single character.

还有什么其他方法可以做到这一点?

What other ways can this be accomplished?

推荐答案

如果是映射/查找,那么通常映射/字典可以解决您的问题.C# 中的此类结构示例:

If it's a mapping/lookup then usually a map/dictionary solves your problem. An example such structure in C#:

string[] inList = new[]{"bee", "kay", "kay", "eff" }; 
Dictionary<string, char> mapping = new Dictionary<string, char> 
   { 
       {"bee", 'b'},
       {"eff", 'f'},
       {"kay", 'k'},
   };

如果您有这样的映射,则只需从映射中查找字母,或将整个字符串列表转换为字符数组.

If you have such a mapping, then just look up the letters from the mapping, or convert the whole list of strings to an array of chars.

char[] chars = inList.Select(s => mapping[s]).ToArray();

几乎所有语言都支持这种类型的数据结构,尽管并非所有语言都支持像最后一个片段这样的函数式结构.在这种情况下,您需要一个循环来构建 out 数组.

Almost all languages supports data structures of this type, although not all support functional constructs like the last snippet. In that case you need a loop to build the out array.

看到你添加了 java 标签.您可以在 java 中完成相同的操作,然后您的字典将成为 java 中的 HashMap.因此,只需服用阿司匹林并查看 如何初始化静态地图?

Saw you added the java tag. You can accomplish the same in java, your dictionary will then be a HashMap in java. So just take an aspirin and look at How can I initialise a static Map?

这篇关于什么是好的 switch 语句替代方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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