Alphabet constant in Java?

前端 未结 2 926
鱼传尺愫
鱼传尺愫 2021-01-05 02:25

I have a situation where I need to find a letter\'s index in the alphabet. In Python I could use string.ascii_lowercase or string.ascii_uppercase.

相关标签:
2条回答
  • 2021-01-05 03:08

    Although I would prefer ColinD's approach whenever it fits I just want to mention that Java actually has some sort of API for this. It allows you to parse numbers with a radix of up to 36 which use the 10 digits from '0'-'9' and the letters 'a'-'z' for the rest of the range (in either case).

    char letter = ...
    int index = Character.digit( letter, 36 ) - 10;
    

    and back

    int index = ...
    char ch = Character.forDigit( index + 10, 36 );
    

    In case you actually want to use this to create or parse radix 36 numbers, you can use the Integer.parseInt and Integer.toString static method implementations that take a radix parameter.

    0 讨论(0)
  • 2021-01-05 03:29

    You can get the index like this:

    char lowercaseLetter = ...
    int index = lowercaseLetter - 'a';
    
    0 讨论(0)
提交回复
热议问题