Reputation: 187
I'm assigned to re-code toUpper and toLower functions. Do I have to write all of 26 alphabets in if statement like:
if ( char == 'a' )
return 'A';
or there is another simple way ?
Upvotes: 0
Views: 58
Reputation: 4788
Lower-case ASCII characters are sequential, so it's a simple case of offsetting the character's value if it is within a given range:
#include <stdio.h>
int to_upper(int value) { return (value >= 'a' && value <= 'z') ? value - ('a'-'A') : value; }
int main(int argc, char *argv[])
{
printf("%c and %c\n", to_upper('B'), to_upper('f'));
return 0;
}
Try this code online here.
Upvotes: 1