goe
goe

Reputation: 5415

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

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

Something like:

int position = get_position('g');

Upvotes: 12

Views: 67694

Answers (4)

sakthivel
sakthivel

Reputation: 1

Take the input of the alphabet:

scanf("%c",ch);

Just subtract 96 from the ascii value of the character. This can be done within the printf argument:

printf("%d",ch-96);

Upvotes: 0

user181548
user181548

Reputation:

This will work with EBCDIC and is case-insensitive:

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

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

Upvotes: 4

cdiggins
cdiggins

Reputation: 18203

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

Upvotes: 4

Greg Hewgill
Greg Hewgill

Reputation: 992955

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

In C, char values are convertible to int values and take on their ASCII values. In this case, 'a' is the same as 97 and 'g' is 103. Since the alphabet is contiguous within the ASCII character set, subtracting 'a' from your value gives its relative position. Add 1 if you consider 'a' to be the first (instead of zeroth) position.

Upvotes: 41

Related Questions