Emi*_*iel 4 java spreadsheet char
我不久前开始编程,目前我需要一种方法来生成一个数组,其中包含前一个字符之后的字符。它应该以 0 处的“A”开头,然后是“1”处的 B 等。困难的部分是使其在“Z”之后是“AA”。
我想出了什么:
public static String[] charArray(int length)
{
String[] res = new String[length];
for(int i = 0; i < length; i++)
{
String name = "";
int colNumber = i;
while(colNumber > 0)
{
char c = (char) ('A' + (colNumber % 26));
name = c + name;
colNumber = colNumber / 26;
}
res[i] = name;
}
return res;
}
Run Code Online (Sandbox Code Playgroud)
这对于字母表的前 26 个字母来说效果很好,但它会生成“... Y, Z, BA, BB, BC...”而不是“... Y, Z, AA, AB, AC...” ”
怎么了?或者有没有更有效或更简单的方法来做到这一点?
提前致谢!
你有一个美好的开始。该示例基本上没有运行 while 循环,而是根据数字 % 26 计算 C 的值
然后,该字母将添加(连接)到数组中以下位置的值:(index / 26) - 1这确保它能够跟上随时间的变化。
第一次迭代时,数组中的每个槽中只有一个字母A B C等。
一旦你浏览完字母表,你就会有一个索引,可以向后查找并将当前字母添加到该值中。
您最终会进入 AAA AAB AAC 等甚至更多。
public static String[] colArray(int length) {
String[] result = new String[length];
String colName = "";
for(int i = 0; i < length; i++) {
char c = (char)('A' + (i % 26));
colName = c + "";
if(i > 25){
colName = result[(i / 26) - 1] + "" + c;
}
result[i] = colName;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2808 次 |
| 最近记录: |