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

如何获得字符';s在C语言字母表中的位置?,c,char,ascii,C,Char,Ascii,有没有一种快速的方法来检索给定字符在C中的英文字母表中的位置 比如: int position = get_position('g'); 在C语言中,char值可转换为int值,并采用ASCII值。在这种情况下,'a'与97相同,'g'为103。由于字母表在ASCII字符集中是连续的,因此从值中减去'a'将给出其相对位置。如果你认为 'A/Eng>是第一个(而不是第0个)位置,则添加1。根据我的经验,从1开始计算通常是危险的,因为它会导致一个错误的结束。根据经验,只有在与用户交互时,我才会转换

有没有一种快速的方法来检索给定字符在C中的英文字母表中的位置

比如:

int position = get_position('g');

在C语言中,
char
值可转换为
int
值,并采用ASCII值。在这种情况下,
'a'
与97相同,
'g'
为103。由于字母表在ASCII字符集中是连续的,因此从值中减去
'a'
将给出其相对位置。如果你认为<代码> 'A/Eng>是第一个(而不是第0个)位置,则添加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;
   }
}
intgetposition(字符c)
{

如果(c>='a'&&c='a'&&c这将适用于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;
}
#包括
#包括
#包括
int getpos(字符c)
{
int pos;
const char*alphabet=“abcdefghijklmnopqrstuvxyz”;
找到常量字符*;
c=更低((无符号字符)c);
found=strchr(字母表c);
pos=已找到-字母表;
如果(!找到)
pos=0;
否则,如果(位置==26)
pos=0;
其他的
pos++;
返回pos;
}
int main()
{
字符测试[]={'A','%','A','z','M',0};
char*c;
对于(c=测试;*c;c++){
printf(“%d\n”,*c-“a”+1);
printf(“%d\n”,getpos(*c));
}
返回0;
}

查看是否要运行它。

请注意,ASCII不是C标准的一部分。它几乎无处不在,足以在您实际可以找到的任何系统上运行。该标准保证字符集中的数字是连续的,而不是字母表(在EBCDIC的情况下,这会把你搞得一团糟,但说真的,谁还会关心EBCDIC呢?)。我爸爸还在COBOL中使用EBCDIC。他维护波音公司的东西。---那么A是字母表中的-31个字母?如何按相反的顺序打印字母表编号,如..1代表z,2代表y等等。你可以使用
tolower()来简化它
toupper()
ctype.h
标题中,这样您就不必同时检查大写和小写。我很欣赏这个答案,因为它考虑了大小写。众所周知,“A”在许多逻辑上下文中与“A”非常不同。
#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;
}