开发者

Alphabet constant in Java?

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. Is there something similar in Java?

Obviously I could do:

private static char[] alphabet = "ab开发者_如何学Ccdefghijklmnopqrstuvwxyz".toCharArray();

But after so much Python, it makes me wonder if this is built in somewhere.


You can get the index like this:

char lowercaseLetter = ...
int index = lowercaseLetter - 'a';


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜