如何用C语言获得字符在字母表中的位置?

有没有一种快速的方法来检索C中英文字母中给定角色的位置?

就像是:

int position = get_position('g'); 

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

在C中, char值可转换为int值并采用其ASCII值。 在这种情况下, 'a'与97相同, 'g'是103.由于字母表在ASCII字符集中是连续的,因此从值中减去'a'会得到它的相对位置。 如果您认为'a'是第一个(而不是第零个)位置,请添加1。

这将与EBCDIC一起使用,并且不区分大小写:

 #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; } 

如果要运行它,请参阅http://codepad.org/5u5uO5ZR 。

你也应该考虑大/小写。 在我的经历中,从1算起,往往是危险的,因为它可能导致一个错误。 根据经验,我总是只在与用户交互时转换为基于1的索引,并在内部使用基于0的计数,以避免混淆。

 int GetPosition(char c) { if (c >= 'a' && c <= 'z') { return c - 'a'; } else if (c >= 'A' && c <= 'Z') { return c - 'A'; } else { // Indicate that it isn't a letter. return -1; } }