Is there a nicer way of converting a number to its alphabetic equivalent than this?
private String getCharForNumber(int i) { char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); if (i > 25) { return null; } return Character.toString(alphabet[i]); }
Maybe something than can deal with numbers greater than 26 more elegantly too?
We can also convert integer into character in Java by adding the character '0' to the integer data type. This is similar to typecasting. The syntax for this method is: char c = (char)(num + '0');
Just make use of the ASCII representation.
private String getCharForNumber(int i) { return i > 0 && i < 27 ? String.valueOf((char)(i + 64)) : null; }
Note: This assumes that i
is between 1
and 26
inclusive.
You'll have to change the condition to i > -1 && i < 26
and the increment to 65
if you want i
to be zero-based.
Here is the full ASCII table, in case you need to refer to:
Edit:
As some folks suggested here, it's much more readable to directly use the character 'A'
instead of its ASCII code.
private String getCharForNumber(int i) { return i > 0 && i < 27 ? String.valueOf((char)(i + 'A' - 1)) : null; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With