Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

c# - Incrementing alphabets

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 the below function to get the results upto Z. It looks like

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

This works fine until 'Z'. It return 'A' if I pass 1 and return 'B' if I pass 2 and so on. But, I am not able to figure out how will I get AA when I pass 27 to this function. I guess I need a recursive method to find it.

Any inputs to this problem will be great!

Edit

This is suggested by Tordek. But his code will fail in numbers like 52, 78 etc. Added workaround for that and here is the final working code.

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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

See this question:
Translate a column index into an Excel Column Name

or this one:
How to convert a column number (eg. 127) into an excel column (eg. AA)

Though the first link has a correct answer right at the top and the 2nd has several that are not correct.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...