Java - how to convert letters in a string to a number?

前端 未结 8 1939
我在风中等你
我在风中等你 2020-12-10 02:33

I\'m quite new to Java so I am wondering how do you convert a letter in a string to a number e.g. hello world would output as 8 5 12 12 15 23 15 18 12 4

相关标签:
8条回答
  • 2020-12-10 03:22

    Usa a Map with the key being the character and an value being the integers. This is not an efficient way - the map should be a static member of the class.

    import java.util.HashMap;
    import java.util.Map;
    
    
    public class JavaApplication1 
    {
        public static void main(String[] args) 
        {
            final Map<Character, Integer> map;
            final String str = "hello world";
    
            map = new HashMap<>();  
            // or map = new HashMap<Character, Integer> if you are using something before Java 7.
            map.put('a', 1);
            map.put('b', 2);
            map.put('c', 3);
            map.put('d', 4);
            map.put('e', 5);
            map.put('f', 6);
            map.put('g', 7);
            map.put('h', 8);
            map.put('i', 9);
            map.put('j', 10);
            map.put('k', 11);
            map.put('l', 12);
            map.put('m', 13);
            map.put('n', 14);
            map.put('o', 15);
            map.put('p', 16);
            map.put('q', 17);
            map.put('r', 18);
            map.put('s', 19);
            map.put('t', 20);
            map.put('u', 21);
            map.put('v', 22);
            map.put('w', 23);
            map.put('x', 24);
            map.put('y', 25);
            map.put('z', 26);
    
            for(final char c : str.toCharArray())
            {
                final Integer val;
    
                val = map.get(c);
    
                if(val == null)
                {   
                    // some sort of error
                }
                else
                {
                    System.out.print(val + " ");
                }
            }
    
            System.out.println();
        }
    }
    
    0 讨论(0)
  • 2020-12-10 03:22

    If you need you can use below tested code to convert string into number if your string contains only numbers and alphabets.

     public static Long getNumericReferenceNumber(String str) {
    
            String result = "";
    
            for (int i = 0; i < str.length(); i++) {
    
                char ch = str.charAt(i);
    
                if (Character.isLetter(ch)) {
                    char initialCharacter = Character.isUpperCase(ch) ? 'A' : 'a';
                    result = result.concat(String.valueOf((ch - initialCharacter + 1)));
                } else result = result + ch;
            }
    
            return Long.parseLong(result);
        }
    
    0 讨论(0)
提交回复
热议问题