开发者

How can I change numbers into letters in C#

I have code like this:

for (in开发者_Python百科t i = 1; i < max; i++)
{
<div>@i</div>
<div>@test[i]</div>
}

I'm using MVC3 razor syntax so it might look a bit strange.

My max is always less than ten and I would like to have a value like "A", "B" .. etc appear between the first instead of the number "1", "2" .. which is the value of i. Is there an easy way I can convert i to a letter where i = 1 represent "A" and i=2 represents "B". I need to do this in C# which I can place in my MVC3 view file.

Marife


Personally I'd probably use the indexer into a string:

// Wherever you want to declare this
// As many as you'll need - the "X" is to put A=1
const string Letters = "XABCDEFGHIJKLMNOP";
...
<div>
for (int i = 1; i < max; i++)
{
<div>@i</div>
<div>@Letters[i]</div>
}

I find that simpler and more flexible than bit shifting etc, although that will certainly work too.


(char)(i + 64) will work (65 = 'A')

for (int i = 1; i < max; i++)
{
    char c = (char)(i + 64); // c will be in [A..J]
    ...
}


You could shift i by 64 (with a 1-based index) and cast your int to a char.


If you don't need to use i anywhere else you can do this:

for (Char ch = 'A'; ch < 'K'; ch++)
{
    MessageBox.Show(ch.ToString());
}

Ah, just realised the last letter isn't constant, so you would need to convert a number somwwehere.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜