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

前端 未结 3 450
梦毁少年i
梦毁少年i 2020-12-16 03:18

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

Something like:

int position = get_position(\'g\');
         


        
3条回答
  •  太阳男子
    2020-12-16 03:32

    This will work with EBCDIC and is case-insensitive:

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

    See http://codepad.org/5u5uO5ZR if you want to run it.

提交回复
热议问题