c# - 递增字母表

标签 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;
}

这在“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/

相关文章:

c# - 使用无状态库在几个类中拆分状态机

c# - 如何用WPF形式绘制一个可以调整大小的形状?

c# - 向 Twilio 发送批量消息 "Bad Request"

javascript - 将字符串中的元音变为大写并将字母更改为字母表中的下一个字母(即 a->b)的程序不起作用

c# - 世界点到等距点 - 需要帮助理解

c# - 是否可以从 IntPtr + 大小创建托管字节数组?

python - 有没有一种快速的方法可以在 Python 中生成字母表的字典?

javascript - 可能的组合并转换为字母算法 - Javascript(Facebook 询问)

接收字母、返回字母表中(从 0 开始)数字位置的 Python 函数

python - 如何将 python 中的字典应用于字符串而不是单个字母