java - 如何将整数转换为 A1 表示法?
问题描述
我正在尝试创建一种方法,该方法将在给定列之后找到下一列。例如:
input: A
output: B
乍一看似乎很简单。我只是打算使用以下方法:
public static char nextLetter(char c) {
c++;
return c;
}
当您越过 Z 列时,就会出现问题。在 Google 表格中,在 Z 列之后,列名是两个字母,然后是三个,等等。所以在列Z
之后AA
,AZ
之后来,之BA
后来等等。我的下一个想法是首先弄清楚根据索引的列位置。所以列将是27、52 等。ZZ
AAA
AA
BA
查找列的索引不是我现在面临的问题。我需要弄清楚如何将该索引转换为相应的列名。本来打算试试下面的方法,结果发现也仅限于AZ:
public static char getLetter(int index) {
return (char) (index + 64);
}
在这一点上,我认为需要一种递归方法。但是,我无法弄清楚如何设置它。据我所知:
private static void getNotation(int size) {
int divided = size / 26;
int remainder = size % 26;
String notation = "";
while (divided % 26 > 0) {
// Here is where the need for a recursive method comes in
}
}
有谁知道将整数(索引)转换为相应列名的好方法?
编辑
我刚刚在 Github 上找到了一个非常有用的资源,它处理十六进制:https ://gist.github.com/pinguet62/9817978
解决方案
我创建了一个示例:
class Test {
static char[] alphabet = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
private static String indexToColumnName(int i) {
if (i >= alphabet.length) {
return indexToColumnName((int)Math.floor(i / alphabet.length) - 1)
+ indexToColumnName(i % alphabet.length);
}
return Character.toString(alphabet[i]);
}
public static void main(String args[]) {
for (int i = 0; i <= 800; ++i) {
System.out.println(i + ": " + indexToColumnName(i));
}
}
}
以上将产生类似:
0: A
1: B
2: C
3: D
...
24: Y
25: Z
26: AA
27: AB
...
700: ZY
701: ZZ
702: AAA
703: AAB
...
在这种情况下,它是零索引,但您可以轻松更改自己。