增加字母表

Nav*_*K N 5 c# alphabet

我正在尝试创建一个函数,它将在传递索引时为我提供字母位置.它会像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;
}
Run Code Online (Sandbox Code Playgroud)

这工作正常,直到'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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Tor*_*dek 4

任何递归函数都可以转换为等效的迭代函数。我发现首先递归思考总是很容易:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

可以简单转换为:

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;
}
Run Code Online (Sandbox Code Playgroud)

即便如此,请听听乔尔的话。