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

前端 未结 3 449
梦毁少年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:57

    You should also probably take into account upper/lower case. In my expereince, counting from 1, is often dangerous because it can lead to off-by-one bugs. As a rule of thumb I always convert to a 1-based index only when interacting with the user, and use 0-based counting internally, to avoid confusion.

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

提交回复
热议问题