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

Categories

I found some question asking how to let char 'B' to return 'C' and then 'D' etc. The answers were quite complex and mostly just overkill.

Why not to use simply this:

char X='A';
X++

EDIT: It goes from A to Z and what next?

See Question&Answers more detail:os

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

1 Answer

If you just want to increment :

Char x = 'A';
Char y = (Char)(Convert.ToUInt16(x) + 1);

But, if you want an excel like column :

    // (1 = A, 2 = B...27 = AA...703 = AAA...)
    public static string GetColNameFromIndex(int columnNumber)
    {
        int dividend = columnNumber;
        string columnName = String.Empty;
        int modulo;

        while (dividend > 0)
        {
            modulo = (dividend - 1) % 26;
            columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
            dividend = (int)((dividend - modulo) / 26);
        }

        return columnName;
    }

    // (A = 1, B = 2...AA = 27...AAA = 703...)
    public static int GetColNumberFromName(string columnName)
    {
        char[] characters = columnName.ToUpperInvariant().ToCharArray();
        int sum = 0;
        for (int i = 0; i < characters.Length; i++)
        {
            sum *= 26;
            sum += (characters[i] - 'A' + 1);
        }
        return sum;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...