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:
-
Lowercase Letters (
'a'
to'z'
):- Returns the position in the alphabet starting from 1.
- Example:
alpha_index('a')
→1
alpha_index('z')
→26
-
Uppercase Letters (
'A'
to'Z'
):- Same as lowercase: returns the 1-based position.
- Example:
alpha_index('A')
→1
alpha_index('Z')
→26
-
Non-Alphabetic Characters:
- Returns
0
for any character outsidea-z
orA-Z
. - Examples:
alpha_index('!')
→0
alpha_index('5')
→0
alpha_index('\0')
→0
- Returns
How It Works:
-
Lowercase Handling:
if (c >= 'a' && c <= 'z') return c - 'a' + 1;
- Computes offset from
'a'
(e.g.,'a' - 'a' = 0
), then adds1
to make it 1-based.
- Computes offset from
-
Uppercase Handling:
if (c >= 'A' && c <= 'Z') return c - 'A' + 1;
- Same logic as lowercase, using
'A'
as the base.
- Same logic as lowercase, using
-
Non-Letter Handling:
return 0; // Default case
Key Notes:
- Case Insensitivity: Treats
'a'
and'A'
the same (both return1
). - ASCII Dependency: Relies on contiguous alphabetic ranges in ASCII (safe for most systems).
- Return Values:
- Letters:
1
to26
. - Non-letters:
0
.
- Letters:
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.