Iterating through the Alphabet - C# a-caz

后端 未结 10 1095
無奈伤痛
無奈伤痛 2020-11-29 03:03

I have a question about iterate through the Alphabet. I would like to have a loop that begins with \"a\" and ends with \"z\". After that, the loop begins \"aa\" and count to

10条回答
  •  不知归路
    2020-11-29 03:34

    I know there are plenty of answers here, and one's been accepted, but IMO they all make it harder than it needs to be. I think the following is simpler and cleaner:

    static string NextColumn(string column){
        char[] c = column.ToCharArray();
        for(int i = c.Length - 1; i >= 0; i--){
            if(char.ToUpper(c[i]++) < 'Z')
                break;
            c[i] -= (char)26;
            if(i == 0)
                return "A" + new string(c);
        }
        return new string(c);
    }
    

    Note that this doesn't do any input validation. If you don't trust your callers, you should add an IsNullOrEmpty check at the beginning, and a c[i] >= 'A' && c[i] <= 'Z' || c[i] >= 'a' && c[i] <= 'z' check at the top of the loop. Or just leave it be and let it be GIGO.

    You may also find use for these companion functions:

    static string GetColumnName(int index){
        StringBuilder txt = new StringBuilder();
        txt.Append((char)('A' + index % 26));
        //txt.Append((char)('A' + --index % 26));
        while((index /= 26) > 0)
            txt.Insert(0, (char)('A' + --index % 26));
        return txt.ToString();
    }
    static int GetColumnIndex(string name){
        int rtn = 0;
        foreach(char c in name)
            rtn = rtn * 26 + (char.ToUpper(c) - '@');
        return rtn - 1;
        //return rtn;
    }
    

    These two functions are zero-based. That is, "A" = 0, "Z" = 25, "AA" = 26, etc. To make them one-based (like Excel's COM interface), remove the line above the commented line in each function, and uncomment those lines.

    As with the NextColumn function, these functions don't validate their inputs. Both with give you garbage if that's what they get.

提交回复
热议问题