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

Rather than giving an error or some sentinel value (e.g. '?') for inputs outside of 0-25, I sometimes find it useful to have a well-defined string for all integers. I like to use the following:

   0 ->    A
   1 ->    B
   2 ->    C
 ...
  25 ->    Z
  26 ->   AA
  27 ->   AB
  28 ->   AC
 ...
 701 ->   ZZ
 702 ->  AAA
 ...

This can be extended to negatives as well:

  -1 ->   -A
  -2 ->   -B
  -3 ->   -C
 ...
 -26 ->   -Z
 -27 ->  -AA
 ...

Java Code:

public static String toAlphabetic(int i) {
    if( i<0 ) {
        return "-"+toAlphabetic(-i-1);
    }

    int quot = i/26;
    int rem = i%26;
    char letter = (char)((int)'A' + rem);
    if( quot == 0 ) {
        return ""+letter;
    } else {
        return toAlphabetic(quot-1) + letter;
    }
}

Python code, including the ability to use alphanumeric (base 36) or case-sensitive (base 62) alphabets:

def to_alphabetic(i,base=26):
    if base < 0 or 62 < base:
        raise ValueError("Invalid base")

    if i < 0:
        return '-'+to_alphabetic(-i-1)

    quot = int(i)/base
    rem = i%base
    if rem < 26:
        letter = chr( ord("A") + rem)
    elif rem < 36:
        letter = str( rem-26)
    else:
        letter = chr( ord("a") + rem - 36)
    if quot == 0:
        return letter
    else:
        return to_alphabetic(quot-1,base) + letter

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;
}

I would return a character char instead of a string.

public static char getChar(int i) {
    return i<0 || i>25 ? '?' : (char)('A' + i);
}

Note: when the character decoder doesn't recognise a character it returns ?

I would use 'A' or 'a' instead of looking up ASCII codes.


Personally, I prefer

return "ABCDEFGHIJKLMNOPQRSTUVWXYZ".substring(i, i+1);

which shares the backing char[]. Alternately, I think the next-most-readable approach is

return Character.toString((char) (i + 'A'));

which doesn't depend on remembering ASCII tables. It doesn't do validation, but if you want to, I'd prefer to write

char c = (char) (i + 'A');
return Character.isUpperCase(c) ? Character.toString(c) : null;

just to make it obvious that you're checking that it's an alphabetic character.

Tags:

Java