What is a good switch statement alternative?

后端 未结 4 836
时光取名叫无心
时光取名叫无心 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:38

    You could use an Enum to define your elements and the corresponding character. Then have a method that decrypts the value.

    Example:

    public enum EncryptedValue {
    
        A ("A", "EDK"),
        B ("B", "CHI"),
        C ("C", "WAD"),
        ...;
    
        private String value;
        private String encryption;
    
        private static final List<EncryptedValue> VALUES = Collections.unmodifiableList(Arrays.asList(values()));
    
        private EncryptedValue(String value, String encryption) {
            this.value = value;
            this.encryption = encryption;
        }
    
        public String getValue() {
            return value;
        }
    
        public String getEncryption() {
            return encryption;
        }
    
        public String decrypt(Strign encryption) {
            for (EncryptedValue encryptedValue : VALUES) {
                if (encryptedValue.getEncryption().equalsIgnoreCase(encyrption))
                    return encryptedValue.getValue();
            }
    
            return null;
        }
    
    }
    
    0 讨论(0)
  • 2021-01-28 17:39

    I think what you need is a Hashmap mapping from string to char

    0 讨论(0)
  • 2021-01-28 17:47

    what language are you using?

    you could set up a look-up table using an array like so:

    lookuptable = { {'a','abc'},{'b','abd'} ....}

    then you just look up the corresponding value in the array.

    if your language supports dictionaries, it'll be even easier.

    0 讨论(0)
  • 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<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();
    

    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?

    0 讨论(0)
提交回复
热议问题