How do I lowercase a string in C?

CStringLowercase

C Problem Overview


How can I convert a mixed case string to a lowercase string in C?

C Solutions


Solution 1 - C

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);

Solution 2 - C

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;

Solution 3 - C

Looping the pointer to gain better performance:

#include <ctype.h>

char* toLower(char* s) {
  for(char *p=s; *p; p++) *p=tolower(*p);
  return s;
}
char* toUpper(char* s) {
  for(char *p=s; *p; p++) *p=toupper(*p);
  return s;
}

Solution 4 - C

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

Solution 5 - C

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.

Solution 6 - C

Are you just dealing with ASCII strings, and have no locale issues? Then yes, that would be a good way to do it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTony StarkView Question on Stackoverflow
Solution 1 - CEarlzView Answer on Stackoverflow
Solution 2 - COleg RazgulyaevView Answer on Stackoverflow
Solution 3 - CcscanView Answer on Stackoverflow
Solution 4 - CEduardoView Answer on Stackoverflow
Solution 5 - CKen SView Answer on Stackoverflow
Solution 6 - CMark ByersView Answer on Stackoverflow