Incrementing alphabets

前端 未结 5 1909
轮回少年
轮回少年 2020-12-19 13:29

I am trying to create a function which will give me alphabet position when an index is passed. It will be same like how excel shows it\'s columns. A...Z, AA,AB.... I wrote t

5条回答
  •  感情败类
    2020-12-19 14:25

    Any recursive function can be converted into an equivalent iterative one. I find it always easy to think recursively first:

    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);
        }
    }
    

    Which can be simple converted into:

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

    Even so, listen to Joel.

提交回复
热议问题