Sunday 20 November 2011

How do you tell whether a character is a letter of the alphabet? in C programming

How do you tell whether a character is a letter of the alphabet?

All letters of the alphabet (including all keys on a computer keyboard) have an assigned number. Together,  these characters and their associated numbers compose the ASCII character set, which is used throughout North America, Europe, and much of the English-speaking world.

The alphabet characters are conveniently grouped into lowercase and uppercase, in numerical order. This arrangement makes it easy to check whether a value is a letter of the alphabet, and also whether the value is uppercase or lowercase. The following example code demonstrates checking a character to see whether it is an alphabet character:

int ch;
ch = getche();
if( (ch >= 97) && (ch <= 122) )
printf(“%c is a lowercase letter\n”, ch);
else if( (ch >= 65) && (ch <= 90) )
print(“%c is an uppercase letter\n”, ch);
else
printf(“%c is not an alphabet letter\n”, ch);

The values that the variable ch is being checked against are decimal values. Of course, you could always check against the character itself, because the ASCII characters are defined in alphabetical order as well as numerical order, as shown in the following code example:
int ch;
ch = getche();
if( (ch >= ‘a’) && (ch <= ‘z’) )
printf(“%c is a lowercase letter\n”, ch);
else if( (ch >= ‘A’) && (ch <= ‘Z’) )
print(“%c is an uppercase letter\n”, ch);
else
printf(“%c is not an alphabet letter\n”, ch);
The method you choose to use in your code is arbitrary. On the other hand, because it is hard to remember every character in the ASCII chart by its decimal equivalent, the latter code example lends itself better to code

readability.

Cross Reference:

XX.19: How do you tell whether a character is a number?

No comments:

Post a Comment