views:

203

answers:

3

is the best/cleanest way to just do a for loop iterating through each position and call tolower() on it?

+1  A: 

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

Mark Byers
what happens if tolower() is called on a non-ascii a-z char? like '!' or '#'. i tested it on '#' and it seemed to work ok. is this generally true for all ascii chars that aren't letters a-z?
hatorade
@hatorade: `tolower()` leaves argument unchanged if it is not in 'A'..'Z' range.
J.F. Sebastian
+4  A: 

It isn't 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:

for(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);
Earlz
`for ( ; *p; ++p) *p = tolower(*p);` seems more idiomatic.
J.F. Sebastian
@J.F. there you go. Depends on if they want the code to look scary or nice :) (very readable one liner, but it does look scary)
Earlz
+1  A: 

to convert to lower case is equivalent to rise bit 0x60:

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

(for latin codepage of course)

oraz
To make it slightly more readable you could do `for(char *p = pstr;*p;++p) *p=*p>='A'`
Grant Peters
This version is actually slower than glibc's `tolower()`. 55.2 vs. 44.15 on my machine.
J.F. Sebastian
i can't imagine that: tolower() deals with chars; only if it's macro
oraz
@oraz: tolower() has `int (*)(int)` signature. Here's the code used for performance measurements http://gist.github.com/370497
J.F. Sebastian
@J.F.: i see, they've used table, but i can optimize: for ( ; *p; ++p) if(*p > 'Z') {continue;} else if (*p < 'A') {continue;} else {*p = *p|0x60;}
oraz
@oraz: `if (*p > 'Z')` optimization performs better on the input I've used, but if there are many upper-case letters it takes the same time as the previous version.
J.F. Sebastian
@J.F.: yes, i see
oraz