How do I lowercase a string in C?

匆匆过客 提交于 2019-11-26 07:27:56

问题


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


回答1:


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



回答2:


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)




回答3:


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




回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/2661766/how-do-i-lowercase-a-string-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!