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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With