我正在尝试创建一个函数,当传递索引时,该函数将给出字母表位置。这与 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(65 + ((index - 1) % alphabetsCount)) + result;
index /= alphabetsCount;
}
return result;
}
即便如此,请听听乔尔的话。
递归是一种可能性 - 如果
index > 26
,您在此调用中处理 index % 26
并将其连接到 index / 26
上的递归调用。 然而,迭代通常更快,并且对于像这样的简单情况来说并不难安排。 伪代码:
string result = <convert `index % 26`>
while index > 26:
index = index / 26
result = <convert `index % 26`> + result
return result
或类似的。
静态字符串 GetColumnName(int index) { 常量 int 字母计数 = 26; 字符串结果 = ''; if (索引 >= 字母数) { 结果 += GetColumnName(index-alphabetsCount) } 返回(字符串)(64 + 索引); }
我的 C# 又糟糕又生锈。将其解释为伪代码 - 它几乎肯定不会编译,但可能会帮助您入门。