C语言 如何在C中小写一个字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2661766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I lowercase a string in C?
提问by Tony Stark
How can I convert a mixed case string to a lowercase string in C?
如何将混合大小写字符串转换为 C 中的小写字符串?
回答by Earlz
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:
或者,如果您更喜欢一种衬垫,那么您可以使用 JF Sebastian 的这种衬垫:
for ( ; *p; ++p) *p = tolower(*p);
回答by Oleg Razgulyaev
to convert to lower case is equivalent to rise bit 0x60:
转换为小写相当于上升位 0x60:
for(char *p = pstr;*p;++p) *p=*p>0x40&&*p<0x5b?*p|0x60:*p;
(for latin codepage of course)
(当然是拉丁代码页)
回答by Eduardo
If you need Unicode support in the lower case function see this question: Light C Unicode Library
如果您需要小写函数中的 Unicode 支持,请参阅此问题: Light C Unicode Library
回答by Ken S
If we're going to be as sloppy as to use tolower(), do this:
如果我们要像使用一样草率tolower(),请执行以下操作:
char blah[] = "blah blah Blah BLAH blAH#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;
}
"; 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.
但是,好吧,如果你给它一些符号/数字,它就会爆炸,而且总的来说它是邪恶的。不过很好的面试问题。
回答by Mark Byers
Are you just dealing with ASCII strings, and have no locale issues? Then yes, that would be a good way to do it.
您是否只处理 ASCII 字符串,并且没有语言环境问题?那么是的,这将是一个很好的方法。
回答by cscan
Looping the pointer to gain better performance:
循环指针以获得更好的性能:
##代码##
