Sams Teach Yourself C in 21 Days

(singke) #1
Manipulating Strings 501

17


String Conversions ..............................................................................................


Many C libraries contain two functions that change the case of characters within a string.
These functions aren’t ANSI standard and, therefore, might differ or not even exist in
your compiler. Because they can be quite useful, they are included here. Their proto-
types, in string.h, are as follows for the Microsoft C compiler (if you use a different com-
piler, they should be similar):
char *strlwr(char *str);
char *strupr(char *str);
The function strlwr()converts all the letter characters in strfrom uppercase to lower-
case;strupr()does the reverse, converting all the characters in strto uppercase.
Nonletter characters aren’t affected. Both functions return str. Note that neither function
actually creates a new string, but both modify the existing string in place. Listing 17.13
demonstrates these functions. Remember that to compile a program that uses non-ANSI
functions, you might need to tell your compiler not to enforce the ANSI standards.

LISTING17.13 upper.c. Converting the case of characters in a string with strlwr()and
strupr()
1: /* The character conversion functions strlwr() and strupr(). */
2:
3: #include <stdio.h>
4: #include <string.h>
5:
6: int main( void )
7: {
8: char buf[80];
9:
10: while (1)
11: {
12: puts(“Enter a line of text, a blank to exit.”);
13: gets(buf);
14:
15: if ( strlen(buf) == 0 )
16: break;
17:
18: puts(strlwr(buf));
19: puts(strupr(buf));
20: }
21: return 0;
22: }

28 448201x-CH17 8/13/02 11:13 AM Page 501

Free download pdf