Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a number to a letter in Java?

Tags:

java

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?

like image 384
edwardmlyte Avatar asked May 30 '12 09:05

edwardmlyte


People also ask

Can we convert int to char in Java?

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


1 Answers

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:


enter image description here


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; } 
like image 194
adarshr Avatar answered Sep 24 '22 03:09

adarshr