C语言 如何将字符串设置为全小写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16909302/
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 to set a string to all lowercase
提问by user2450044
I have a char foo[SIZE]; //(string)
我有一个 char foo[SIZE]; //(string)
and have inputed it correctly using %s(as in it printfsthe correct input), but now want to set it to lowercase. So I tried using
并使用正确输入%s(如printfs正确输入),但现在想将其设置为小写。所以我尝试使用
if (isupper(*foo))
*foo=tolower(*foo);
ie when I do:
即当我这样做时:
printf("%s" foo); //I get the same text with upper case
The text does not seem to change. Thank you.
文字似乎没有变化。谢谢你。
回答by Jerry Coffin
fooisn't a pointer, so you don't want to use it as one. You also don't have to check whether a character is an upper-case letter before using tolower-- it converts upper to lower case, and leaves other characters unchanged. You probably want something like:
foo不是指针,因此您不想将其用作指针。您也不必在使用前检查字符是否为大写字母tolower——它将大写字母转换为小写字母,而其他字符保持不变。你可能想要这样的东西:
for (i=0; foo[i]; i++)
foo[i] = tolower((unsigned char)foo[i]);
Note that when you call tolower(and toupper, isalpha, etc.) you really need to cast your input to unsigned char. Otherwise, many (most?) characters outside the basic English/ASCII character set will frequently lead to undefined behavior (e.g., in a typical case, most accented characters will show up as negative numbers).
请注意,当您调用tolower(和toupper、isalpha等)时,您确实需要将输入转换为unsigned char. 否则,基本英语/ASCII 字符集之外的许多(大多数?)字符将经常导致未定义的行为(例如,在典型情况下,大多数重音字符将显示为负数)。
As an aside, when you're reading the string, you don't want to use scanfwith %s-- you always want to specify the string length, something like: scanf("%19s", foo);, assuming SIZE== 20 (i.e., you want to specify one less than the size. Alternatively, you could use fgets, like fgets(foo, 20, infile);. Note that with fgets, you specify the size of the buffer, not one less like you do with scanf(and company like fscanf).
顺便说一句,当您读取字符串时,您不想使用scanfwith %s-- 您总是想指定字符串长度,例如: scanf("%19s", foo);,假设SIZE== 20(即,您想指定一个小于大小。或者,您可以使用fgets,例如fgets(foo, 20, infile);。请注意,使用fgets,您指定缓冲区的大小,而不是像您使用的那样scanf(以及像 fscanf这样的公司)。
回答by Bill
Try this
尝试这个
for(i = 0; foo[i]; i++){
foo[i] = tolower(foo[i]);
}
回答by Grzegorz Piwowarek
*foo=tolower(*foo); //doing *(foo+i) or foo[i] does not work either
*foo=tolower(*foo); //doing *(foo+i) or foo[i] does not work either
because all of those options do not make sense
因为所有这些选项都没有意义
You should use it like this:
你应该像这样使用它:
for(i = 0; foo[i] != '##代码##'; i++){
foo[i] = tolower(foo[i]);
}

