Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement toLower() if you get toUpper() already

Tags:

c

Suppose you get the function toUpper() already, which is defined as int toUpper(char), How can you implement the function toLower(), which is int toLower(char). Thanks.

like image 773
Jeffrey.W.Dong Avatar asked Feb 01 '11 03:02

Jeffrey.W.Dong


2 Answers

I suppose this is one way that uses the existing implementation of toUpper (note that toLower and toUpper are defined as eating int and I have done so accordingly; I am assuming that you have a typo in your OP):

int toLower(int c) {
    for(int i = 0; i <= UCHAR_MAX; i++) {
        if(c != i && toUpper(i) == c) {
            return i;
        }
    }
    return c;
}

Edit: Thanks, Chris Lutz.

like image 100
jason Avatar answered Oct 20 '22 04:10

jason


The only proper way I can see to do this is:

int toLower(int c)
{
    if(toUpper(c) != c) return c; // keep lowercase characters unchanged
    if(!isalpha(c)) return c;
    return c - 'A' + 'a'; // nonportable hack, only works for ASCII
}

Technically, the last line should be a full-blown switch statement, or something like:

static char lower[] = "abcdefghijklmnopqrstuvwxyz";
static char upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// ...
return lower[strchr(upper, c) - upper];

Because the standard doesn't guarantee that alphabetical characters are consecutive in the character set. However, ASCII support is "good enough" for most people.

like image 2
Chris Lutz Avatar answered Oct 20 '22 04:10

Chris Lutz