如何将字符串设置为全小写 [英] How to set a string to all lowercase

查看:32
本文介绍了如何将字符串设置为全小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 char foo[SIZE];//(字符串)

并且已经使用 %s 正确输入了它(就像在它 printfs 中正确输入一样),但现在想将它设置为小写.所以我尝试使用

and have inputed it correctly using %s (as in it printfs the correct input), but now want to set it to lowercase. So I tried using

 if (isupper(*foo)) 
   *foo=tolower(*foo); 

即当我这样做时:

printf("%s" foo); //I get the same text with upper case

文本似乎没有改变.谢谢你.

The text does not seem to change. Thank you.

推荐答案

foo 不是指针,因此您不想将其用作指针.您也不必在使用 tolower 之前检查字符是否为大写字母——它会将大写转换为小写,而其他字符保持不变.你可能想要这样的东西:

foo isn'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:

for (i=0; foo[i]; i++)
    foo[i] = tolower((unsigned char)foo[i]);

请注意,当您调用 tolower(以及 toupperisalpha 等)时,您确实需要将输入转换为 无符号字符.否则,基本英语/ASCII 字符集之外的许多(大多数?)字符将经常导致未定义的行为(例如,在典型情况下,大多数重音字符将显示为负数).

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

顺便说一句,当您读取字符串时,您不想将 scanf%s 一起使用——您总是想指定字符串长度, 类似于:scanf("%19s", foo);,假设 SIZE == 20(即,您希望指定比大小少 1.或者,您可以使用 fgets,例如 fgets(foo, 20, infile);.请注意,使用 fgets,您指定缓冲区的大小,而不是与您对 scanf(以及像 fscanf 这样的公司)所做的不同.

As an aside, when you're reading the string, you don't want to use scanf with %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).

这篇关于如何将字符串设置为全小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆