What is a good switch statement alternative?

后端 未结 4 834
时光取名叫无心
时光取名叫无心 2021-01-28 16:48

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.<

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-28 17:51

    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 mapping = new Dictionary 
       { 
           {"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();
    

    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.

    EDIT: 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?

提交回复
热议问题