The `alpha_index` function - kevshouse/exam_quest GitHub Wiki

The alpha_index function determines the 1-based position of a character in the alphabet if it's a letter (case-insensitive), or returns 0 for non-alphabetic characters. Here's a detailed breakdown:

Behavior:

  1. Lowercase Letters ('a' to 'z'):

    • Returns the position in the alphabet starting from 1.
    • Example:
      alpha_index('a')1
      alpha_index('z')26
  2. Uppercase Letters ('A' to 'Z'):

    • Same as lowercase: returns the 1-based position.
    • Example:
      alpha_index('A')1
      alpha_index('Z')26
  3. Non-Alphabetic Characters:

    • Returns 0 for any character outside a-z or A-Z.
    • Examples:
      alpha_index('!')0
      alpha_index('5')0
      alpha_index('\0')0

How It Works:

  • Lowercase Handling:

    if (c >= 'a' && c <= 'z') 
        return c - 'a' + 1;
    
    • Computes offset from 'a' (e.g., 'a' - 'a' = 0), then adds 1 to make it 1-based.
  • Uppercase Handling:

    if (c >= 'A' && c <= 'Z') 
        return c - 'A' + 1;
    
    • Same logic as lowercase, using 'A' as the base.
  • Non-Letter Handling:

    return 0;  // Default case
    

Key Notes:

  • Case Insensitivity: Treats 'a' and 'A' the same (both return 1).
  • ASCII Dependency: Relies on contiguous alphabetic ranges in ASCII (safe for most systems).
  • Return Values:
    • Letters: 1 to 26.
    • Non-letters: 0.

Example Outputs:

Input Output Explanation
'd' 4 4th letter (lowercase)
'M' 13 13th letter (uppercase)
'@' 0 Not a letter
' ' 0 Space (non-letter)

This function is useful for mapping alphabetic characters to numeric positions while ignoring case and filtering out non-letters.