What is a good switch statement alternative?(什么是好的 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 语句替代方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:什么是好的 switch 语句替代方案?


- 如何使用WebFilter实现授权头检查 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01