How to set a string to all lowercase
Solution 1
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]);
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).
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).
Solution 2
Try this
for(i = 0; foo[i]; i++){
foo[i] = tolower(foo[i]);
}
Solution 3
*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] != '\0'; i++){
foo[i] = tolower(foo[i]);
}
user2450044
Updated on June 04, 2020Comments
-
user2450044 almost 4 years
I have a
char foo[SIZE]; //(string)
and have inputed it correctly using
%s
(as in itprintfs
the correct input), but now want to set it to lowercase. So I tried usingif (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.
-
Bill almost 11 years+1 for the "
aside....
" part -
user2450044 almost 11 yearswhat does the foo[i] in the middle mean?
-
user2450044 almost 11 yearswhat does the foo[i] in the middle of the for loop mean? is that like i<foo?
-
Bill almost 11 years@user2450044 your char array is/should be null terminated...and then that
foo[i]
is evaluated tofalse
when the end of the array is reached. -
Bill almost 11 yearsNULL or
\0
?? I think\0
is better since it is a char array. -
Bill almost 11 years@user2450044 You can use
foo[i] != '\0'
, but NOTi <'\0'
. -
Grzegorz Piwowarek almost 11 years@Bill You're right. Thanks
-
Bill almost 11 yearsok, now +1 for the answer :)
-
Admin almost 11 years@user2450044 ever read about for loops in C? Make some effort man, seriously...