Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I lowercase a string in C?

People also ask

How do you make letters lowercase in C?

C tolower() The tolower() function takes an uppercase alphabet and convert it to a lowercase character. If the arguments passed to the tolower() function is other than an uppercase alphabet, it returns the same character that is passed to the function. It is defined in ctype.

Is there a lowercase function in C?

In C, the tolower() function is used to convert uppercase letters to lowercase. When an uppercase letter is passed into the tolower() function, it converts it into lowercase. However, when a lowercase letter is passed into the tolower() function, it returns the same letter. Note: In order to use this function, ctype.

How do you Uncapitalize a string?

lower() Return value lower() method returns the lowercase string from the given string. It converts all uppercase characters to lowercase. If no uppercase characters exist, it returns the original string.

Can you use tolower on a string in C?

To convert a given string to lowercase in C language, iterate over characters of the string and convert each character to lowercase using tolower() function.


It's in the standard library, and that's the most straight forward way I can see to implement such a function. So yes, just loop through the string and convert each character to lowercase.

Something trivial like this:

#include <ctype.h>

for(int i = 0; str[i]; i++){
  str[i] = tolower(str[i]);
}

or if you prefer one liners, then you can use this one by J.F. Sebastian:

for ( ; *p; ++p) *p = tolower(*p);

to convert to lower case is equivalent to rise bit 0x60 if you restrict yourself to ASCII:

for(char *p = pstr; *p; ++p)
    *p = *p > 0x40 && *p < 0x5b ? *p | 0x60 : *p;

If you need Unicode support in the lower case function see this question: Light C Unicode Library


If we're going to be as sloppy as to use tolower(), do this:

char blah[] = "blah blah Blah BLAH blAH\0";
int i = 0;
while( blah[i] |=' ', blah[++i] ) {}

But, well, it kinda explodes if you feed it some symbols/numerals, and in general it's evil. Good interview question, though.