-1

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;
    }
Norbert Willhelm
  • 2,579
  • 1
  • 23
  • 33
  • 4
    It seems to use ASCII character values. But to be honest, I'm a little confused how you could have written this code without understanding how it works. – grooveplex Jan 27 '19 at 18:16
  • ASCII codes, the letter `a` is integer 97 hence why it subtracts 96. But this question really doesn't belong here. – DavidG Jan 27 '19 at 18:16
  • Only works for lowercase letters, though. – Crusha K. Rool Jan 27 '19 at 18:17
  • You should probably understand what the [Ascii *Table*](http://www.asciitable.com/) is. – Erik Philips Jan 27 '19 at 18:17
  • @CrushaK.Rool ...and only for ASCII. – grooveplex Jan 27 '19 at 18:17
  • Beforehand I convert my string to lowercase. – Norbert Willhelm Jan 27 '19 at 18:19
  • 1
    I'm really interested, why everybody mentions ASCII? `char` represents `Unicode` symbol. – Woldemar89 Jan 27 '19 at 18:40
  • @NorbertWillhelm I'm going to disagree with this explanation. Getting letter number can be actual not only for English alphabet exactly because `char` is Unicode character. You can set hardcoded integer constants to 1072, 1105, 1071 and method will be returning actual Russian letter number for Russian alphabet for example. This is just a coincidence and historical reason there is English alphabet in the ASCII table, but not another. – Woldemar89 Jan 27 '19 at 19:13

2 Answers2

1

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
Cem YILMAZ
  • 134
  • 2
  • 6
0

in the ASCII code table the small "a" starts at position 97 in a row. Therefore you only have to subtract 96 from its ASCII postion. Your code only works for lowercase letters, and only for letters within the ASCII range.

grooveplex
  • 2,492
  • 4
  • 28
  • 30
Falco Alexander
  • 3,092
  • 2
  • 20
  • 39