This is a toupper and tolower implementation for whole c-strings, without making use of the existing toupper and tolower functions for characters :)


char s[]="Hello, beautiful world!";
stoupper(s); // s now contains: `HELLO, BEAUTIFUL WORLD!´
stolower(s); // s now contains: `hello, beautiful world!´
@author: Mathias Van Malderen (tux4life)

void stoupper(char *s)
    for(; *s; s++)
        if(('a' <= *s) && (*s <= 'z'))
            *s = 'A' + (*s - 'a');

void stolower(char *s)
    for(; *s; s++)
        if(('A' <= *s) && (*s <= 'Z'))
            *s = 'a' + (*s - 'A');
7 Years
Discussion Span
Last Post by William Hemsworth

Shorter, but perhaps not any more efficient.

void stoupper(char *s) {
  do if (96 == (224 & *s)) *s &= 223;
  while (*s++);

Wow, I'm competitive. No doubt there's some mistake in mine though.

Here's how it works:

the first lowercase letter 'a' has a binary of: 01100001
the last lowercase letter 'z' has a binary of: 01111010

Both these letters have 01100000 in common.
But if the bit 10000000 is on, then it cant be a letter.

So by doing an AND check with 11100000 and comparing (==) it with the value 01100000, it should determine whether or not the character is a valid lowercase letter.

Then remove the bit 00100000 to make the character a capital.

Am I good or what? :D


Works only for ASCII. Your résumé will be uppercased to RéSUMé or bungle the e with accent. Nice, isn't it?


Obviously only works with ascii and doesn't support unicode, otherwise char* would have been used. Either way, using the toupper function there outputs: RÚSUMÚ for me (even though it's most probably just a font problem). I would rather it printed RéSUMé :] Both these codes simply turn any characters between 'a' to 'z' and makes them uppercase.


Hi, naply, take a look at this and you'll see that toupper only converts alphabet letters to uppercase (this is analog for tolower), I intended my code to do 'exactly' the same :)

WH>Am I good or what?
Yes, you're the best :P


unsigned char string[];

///////// Convert entire string: uppercase to lowercase ////////

for (i=0; i<strlen(string); i++)
if (isupper(string))

///////// Convert entire string: lowercase to uppercase ////////

for (i=0; i<strlen(string); i++)
if (islower(string))

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.