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

前端 未结 8 1943
我在风中等你
我在风中等你 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

    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);
        }
    

提交回复
热议问题