Jeffrey.W.Dong
Jeffrey.W.Dong

Reputation: 61

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

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.

Upvotes: 5

Views: 2924

Answers (3)

jason
jason

Reputation: 241701

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.

Upvotes: 3

Chris Lutz
Chris Lutz

Reputation: 75429

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.

Upvotes: 2

Jerry Coffin
Jerry Coffin

Reputation: 490378

Create two parallel arrays (A and B), each large enough to hold the entire character set. Step through all the values in A, and replace each value with toUpper(value). Then step through B, and everywhere A differs, replace B[A[value]] with B[value] (i.e., everywhere toUpper replaced a value with an upper-case version, replace the upper-case version in B with the lower-case version from which it was converted). Once you're done, toLower just returns B[value] (and A can be discarded).

This assumes that you're dealing with upper/lower case that form a bijection (which, I should add, isn't always the case -- but I believe that assumption is implicit in the question).

Upvotes: 0

Related Questions