is the best/cleanest way to just do a for loop iterating through each position and call tolower()
on it?
views:
203answers:
3
+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
2010-04-18 09:43:26
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
2010-04-18 10:29:41
@hatorade: `tolower()` leaves argument unchanged if it is not in 'A'..'Z' range.
J.F. Sebastian
2010-04-18 18:20:42
+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
2010-04-18 09:44:18
@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
2010-04-18 10:05:50
+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
2010-04-18 10:36:15
To make it slightly more readable you could do `for(char *p = pstr;*p;++p) *p=*p>='A'`
Grant Peters
2010-04-18 10:54:03
This version is actually slower than glibc's `tolower()`. 55.2 vs. 44.15 on my machine.
J.F. Sebastian
2010-04-18 18:10:46
@oraz: tolower() has `int (*)(int)` signature. Here's the code used for performance measurements http://gist.github.com/370497
J.F. Sebastian
2010-04-18 19:32:56
@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
2010-04-18 20:27:07
@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
2010-04-18 21:33:44