为什么我的 C# 函数返回字母表中字母的位置有效?

Why does my C# function returning the position of a letter in the alphabet work?

我有一个函数 returns 一个字母在字母表中的位置。它是如何工作的?

这是我的 C# 的样子:

    private int CalculateLetterPosition(char cCharacter)
    {
        int iReturn = 0;
        int iCharacterValue = (int)cCharacter;
        if (iCharacterValue >= 97 && iCharacterValue <= 122)
        {
            iReturn = iCharacterValue - 96;
        }
        return iReturn;
    }

ASCII 代码 table 中,小的 "a" 从连续的位置 97 开始。 因此,您只需从其 ASCII 位置减去 96。您的代码仅适用于小写字母,并且仅适用于 ASCII 范围内的字母。

所以所有字母(或chars)都有数字表示。基本上,

  1. 您的代码将文本字符值转换为其 ASCII 数值。
  2. 从数值中减去 96,因为 97 是 'a' 的 ASCII 码。
  3. 最终结果将是字母表中的位置。

例如:

您为您的函数提供 b

  • b 代表 98 在 ASCII table.
  • 98 - 96 = 2