如何在Java中将数字转换为字母? [英] How do I convert a number to a letter in 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]);
}
也许可以优雅地处理大于26的数字呢?
Maybe something than can deal with numbers greater than 26 more elegantly too?
推荐答案
只需使用ASCII表示形式即可.
Just make use of the ASCII representation.
private String getCharForNumber(int i) {
return i > 0 && i < 27 ? String.valueOf((char)(i + 64)) : null;
}
注意:这假定i
在1
和26
之间(包括两端).
Note: This assumes that i
is between 1
and 26
inclusive.
如果希望i
从零开始,则必须将条件更改为i > -1 && i < 26
,并将增量更改为65
.
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.
这里是完整的ASCII表,以防您需要参考:
Here is the full ASCII table, in case you need to refer to:
正如一些人在这里建议的那样,直接使用字符'A'
而不是其ASCII代码更具可读性.
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;
}
这篇关于如何在Java中将数字转换为字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!