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

前端 未结 8 1938
我在风中等你
我在风中等你 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:02
    String s = "hello world";
    String t = "";
    for (int i = 0; i < s.length(); ++i) {
        char ch = s.charAt(i);
        if (!t.isEmpty()) {
            t += " ";
        }
        int n = (int)ch - (int)'a' + 1;
        t += String.valueOf(n);
    }
    System.out.println(t);
    

    This does not deal with space etc.

    0 讨论(0)
  • 2020-12-10 03:05

    You can do something like:

    for (int i = 0; i < a.length(); ++i) {
      if (a.charAt(i) >= 'a' && a.charAt(i) <= 'z') {
        System.out.println((int)a.charAt(i) - (int)'a');
      } 
    }
    
    0 讨论(0)
  • 2020-12-10 03:07

    I have added all the characters to get a fair result:

    public static long stringToNumber(String s) {
        long result = 0;
    
        for (int i = 0; i < s.length(); i++) {
            final char ch = s.charAt(i);
            result += (int) ch;
        }
    
        return result;
    }
    
    0 讨论(0)
  • 2020-12-10 03:13

    for each character at posotion i: output s.charAt(i)-'a'+1. s is the string.

    0 讨论(0)
  • 2020-12-10 03:16
    public static void main(String[] args) {
        String s = "hello world";
        s = s.replace(" ", "");
        char[] c = s.toCharArray();
    
        for (Character ss : c)
            System.out.println(ss - 'a' + 1);
    }
    
    0 讨论(0)
  • 2020-12-10 03:21

    Since this is most likely a learning assignment, I'll give you a hint: all UNICODE code points for the letters of the Latin alphabet are ordered alphabetically. If the code of a is some number N, then the code of b is N+1, the code of c is N+2, and so on; the code of Z is N+26.

    You can subtract character code points in the same way that you subtract integers. Since the code points are alphabetized, the following calculation

    char ch = 'h';
    int pos = ch - 'a' + 1;
    

    produces the sequence number of h, i.e. 8. If you perform this calculation in a loop, you would get the result that you need.

    Note that the above formula works only with characters of the same register. If your input string is in mixed case, you need to convert each character to lower case before doing the calculation, otherwise it would come out wrong.

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