我正在尝试创建一个函数,它会在传递索引时为我提供字母表位置。它与 excel 显示其列的方式相同。 A...Z, AA,AB.... 我写了下面的函数来得到 Z 的结果。它看起来像
static string GetColumnName(int index)
{
const int alphabetsCount = 26;
if (index <= alphabetsCount)
{
int code = (index - 1) + (int)'A';
return char.ConvertFromUtf32(code);
}
return string.Empty;
}
这在“Z”之前工作正常。如果我通过 1,它返回“A”;如果我通过 2,它返回“B”,依此类推。但是,当我将 27 传递给此函数时,我无法弄清楚如何获得 AA。我想我需要一个递归方法来找到它。
对此问题的任何输入都会很棒!
编辑
这是 Tordek 建议的。但是他的代码会在 52、78 等数字中失败。为此添加了解决方法,这是最终的工作代码。
static string GetColumnName(int index)
{
const int alphabetsCount = 26;
if (index > alphabetsCount)
{
int mod = index % alphabetsCount;
int columnIndex = index / alphabetsCount;
// if mod is 0 (clearly divisible) we reached end of one combination. Something like AZ
if (mod == 0)
{
// reducing column index as index / alphabetsCount will give the next value and we will miss one column.
columnIndex -= 1;
// passing 0 to the function will return character '@' which is invalid
// mod should be the alphabets count. So it takes the last char in the alphabet.
mod = alphabetsCount;
}
return GetColumnName(columnIndex) + GetColumnName(mod);
}
else
{
int code = (index - 1) + (int)'A';
return char.ConvertFromUtf32(code);
}
}
最佳答案
任何递归函数都可以转换为等价的迭代函数。我发现首先递归思考总是很容易:
static string GetColumnName(int index)
{
const int alphabetsCount = 26;
if (index > alphabetsCount) {
return GetColumnName(index / alphabetsCount) + GetColumnName(index % alphabetsCount);
} else {
int code = (index - 1) + (int)'A';
return char.ConvertFromUtf32(code);
}
}
可以简单的转换成:
static string GetColumnName(int index)
{
const int alphabetsCount = 26;
string result = string.Empty;
while (index > 0) {
result = char.ConvertFromUtf32(64 + (index % alphabetsCount)) + result;
index /= alphabetsCount;
}
return result;
}
即便如此,还是听听乔尔的话。
关于c# - 递增字母表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/924109/