将字母表中的字母位置转换为C#中的数字

Converting letter position in the alphabet to numbers in C#

我需要将字母转换成数字。 A 为 01,B 为 02 ... Z 为 26.

我的伪代码:

variable = 'C'

if (variable = 'A'){
counter = 01}else if (variable = 'B'){
counter = 02}else if (variable = 'C'){
counter = 03
}elseif...

肯定有另一种方法可以做到这一点。

尝试:

var x = 'A' - 'A' + 1 //01
var x = 'Z' - 'A' + 1 //26

如果这些字母都是大写 ASCII 字母,你可以很容易地这样做:

int ascii = (int)Char.GetNumericValue(variable);
if(ascii >= 65 && ascii <= 90)
{
    counter = ascii - 64;
}
else if //...

每个字符都有自己的 ascii 代码,例如 "A" 从 65 开始,所以基本上您只需从每个字符中减去 64 即可得到您的数字。 "A" - 64 = 1 "B" - 64 = 2...

private String Number2String(int number, bool isCaps)
{
    Char c = (Char)((isCaps ? 65 : 97) + (number - 1));
    return c.ToString();
}
int charToDigit(char character){
    return character-64; //or character-0x40 if you prefer hex
}

这将简单地将 ASCII char 转换为其对应的 int 并将其下拉为 1。

由于'A'在ASCII中是65或0x41,减去64./0x40时结果为1。如果您希望 'A' 为 0,则减去 0x40。