如何在C语言中的字母中获取字符的位置?

问题描述:

是否有一种快速的方法来检索C中英文字母中给定字符的位置?

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

类似:

int position = get_position('g');

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

在C中,char值可转换为int值,并采用其ASCII值.在这种情况下,'a'与97相同,而'g'为103.由于字母表在ASCII字符集中是连续的,因此从值中减去'a'即可得到其相对位置.如果您认为'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.