Search code examples
c#functionletteralphabet

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


I have a function that returns the position of a letter in the alphabet. How does it work?

This is how my C# looks like:

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

Solution

  • So all letters(or chars) have numeric representations. Basically,

    1. Your code casts the text char value to its ASCII numeric value.
    2. Subtracts 96 from the numeric value since 97 is the ASCII code for 'a'.
    3. Final result will be the position in the alphabet.

    For example:

    You provide b to your function.

    • b stands for 98 in ASCII table.
    • 98 - 96 = 2