开发者

How do I convert integers to characters in C#?

I am trying to convert an index of 1 to 27 into the corresponding uppercase letter. I know that in C++ I could type this:

char letter = 'A' + (char)(myIndex % 27);
开发者_如何学Go

This same code does not work in C#. How can I accomplish this task in C#?

EDIT: I'd rather not have to encode an enum or switch statement for this if there is a better mathematical solution like the one above.


When you add (or subtract) two characters, you get an Int32 in C#. This will work:

int letter = 'A' + (char)(myIndex % 27);

If you want a char, you need to explicitly cast it again:

char letter = (char) ('A' + (char)(myIndex % 27));

However, this most likely should actually be:

char letter = (char) ('A' + (char)((myIndex - 1) % 26));


Here is a table driven solution:

char ToUpperChar(int index)
{
    if (index < 1 || index > 26)
        throw new ArgumentOutOfRangeException("index");

    return "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[index-1]; // took out the % - it's range-checked above.
}


char letter = (char)('A' + (myIndex-1)%26);

(edit out magic number, adjusted indices)


In C#, you'll have to do your casting slightly differently:

char letter = (char)('A' + (myIndex % 27));

However, your math might also be wrong, and this is probably closer to what you actually want:

char letter = (char)('A' + ((myIndex - 1) % 26));


How about an extension method?

    public static int Index(this char letter)
    {
        const int offset = 64;
        if(letter >= 'A' && letter <= 'Z')
            return (Convert.ToInt32(letter) - offset);
        return 0;
    }

//usage... char letter = 'A'; int index = letter.Index();


This should work...

byte upperA = 65;
byte index = 1;

char letter = (char)(upperA + (index % 27));

Console.WriteLine(letter);

I also like Reed's answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜