Incrementation of char

2019-01-18 03:16发布

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?

标签: c# char
3条回答
Fickle 薄情
2楼-- · 2019-01-18 03:32

If you're happy with the results that gives, then that's fine.

Usually when I've seen questions like that, they want to wrap from "Z" to "AA" or something like that that though - like Excel columns. Clearly just incrementing a char won't do that - it would go to '['.

Alternatively, even within a single character, the range of valid values may be non-contiguous - the obvious example being hex. If you increment '9' you get ':' instead of the 'a' or 'A' which you probably wanted. The desired order is rarely "whatever Unicode gives you".

查看更多
Ridiculous、
3楼-- · 2019-01-18 03:34

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;
    }
查看更多
ら.Afraid
4楼-- · 2019-01-18 03:38

Probably because it is also intended to go from Z to AA, ala Perl and PHP.

查看更多
登录 后发表回答