【发布时间】:2010-12-09 15:46:48
【问题描述】:
有没有一种快速的方法来检索给定字符在 C 中英文字母表中的位置?
类似:
int position = get_position('g');
【问题讨论】:
有没有一种快速的方法来检索给定字符在 C 中英文字母表中的位置?
类似:
int position = get_position('g');
【问题讨论】:
int position = 'g' - 'a' + 1;
在 C 中,char 值可转换为 int 值并采用其 ASCII 值。在这种情况下,'a' 与 97 相同,'g' 为 103。由于字母在 ASCII 字符集中是连续的,因此从您的值中减去 'a' 即可得出其相对位置。如果您认为'a' 是第一个(而不是第零个)位置,则添加 1。
【讨论】:
您还应该考虑大写/小写。根据我的经验,从 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;
}
}
【讨论】:
ctype.h 标头中使用tolower() 或toupper() 来简化它,这样您就不必同时检查大小写。
这将适用于 EBCDIC 并且不区分大小写:
#include <ctype.h>
#include <stdio.h>
#include <string.h>
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。
【讨论】:
输入字母表:
scanf("%c",ch);
只需从字符的 ascii 值中减去 96。这可以在 printf 参数中完成:
printf("%d",ch-96);
【讨论】: