gpt4 book ai didi

java - 如何将整数转换为 A1 表示法?

转载 作者:行者123 更新时间:2023-12-05 00:09:56 25 4
gpt4 key购买 nike

我正在尝试创建一种方法,可以在给定列之后找到下一列。例如:

input: A
output: B

乍一看似乎很简单。我只是打算使用以下方法:
public static char nextLetter(char c) {
c++;
return c;
}

当你越过 Z 列时就会出现问题。在 Google 表格中,在 Z 列之后,列名是两个字母,然后是三个字母,依此类推。所以在 Z 列之后来 AA , 之后 AZBA , 之后 ZZAAA等。我的下一个想法是首先根据索引找出列的位置。所以专栏 AA将 27, BA 52等

查找列的索引不是我现在面临的问题。我需要弄清楚如何将该索引转换为相应的列名。我打算尝试以下方法,但我意识到它也仅限于 A-Z:
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
...

在这种情况下,它是零索引,但您可以轻松地改变自己。

关于java - 如何将整数转换为 A1 表示法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59401548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com