Is there a quick way to retrieve given character\'s position in the english alphabet in C?
Something like:
int position = get_position(\'g\');
This will work with EBCDIC and is case-insensitive:
#include
#include
#include
int getpos (char c)
{
int pos;
const char * alphabet = "abcdefghijklmnopqrstuvwxyz";
const char * found;
c = tolower ((unsigned char)c);
found = strchr (alphabet, c);
pos = found - alphabet;
if (!found)
pos = 0;
else if (pos == 26)
pos = 0;
else
pos++;
return pos;
}
int main ()
{
char tests[] = {'A', '%', 'a', 'z', 'M', 0};
char * c;
for (c = tests; *c; c++) {
printf ("%d\n", *c - 'a' + 1);
printf ("%d\n", getpos (*c));
}
return 0;
}
See http://codepad.org/5u5uO5ZR if you want to run it.