Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get character's position in alphabet in C language?

Tags:

c

char

ascii

Is there a quick way to retrieve given character's position in the english alphabet in C?

Something like:

int position = get_position('g');
like image 820
goe Avatar asked Oct 24 '09 01:10

goe


1 Answers

int position = 'g' - 'a' + 1;

In C, char values are convertible to int values and take on their ASCII values. In this case, 'a' is the same as 97 and 'g' is 103. Since the alphabet is contiguous within the ASCII character set, subtracting 'a' from your value gives its relative position. Add 1 if you consider 'a' to be the first (instead of zeroth) position.

like image 151
Greg Hewgill Avatar answered Oct 01 '22 07:10

Greg Hewgill