Sams Teach Yourself C in 21 Days

(singke) #1
Manipulating Strings 491

17


Comparing Two Entire Strings ......................................................................

The function strcmp()compares two strings, character by character. Its prototype is
int strcmp(const char *str1, const char *str2);
The arguments str1andstr2are pointers to the strings being compared. The function’s
return values are given in Table 17.1. You should notice that both strings are past as con-
stants because neither will be changed. Listing 17.7 demonstrates strcmp().

TABLE17.1 The values returned by strcmp()
Return Value Meaning
< 0 str1is less than str2.
0 str1is equal to str2.
> 0 str1is greater than str2.

LISTING17.7 strcmp.c. Using strcmp()to compare strings
1: /* The strcmp() function. */
2:
3: #include <stdio.h>
4: #include <string.h>
5:
6: int main( void )
7: {
8: char str1[80], str2[80];
9: int x;
10:
11: while (1)
12: {
13:
14: /* Input two strings. */
15:
16: printf(“\n\nInput the first string, a blank to exit: “);
17: gets(str1);
18:
19: if ( strlen(str1) == 0 )
20: break;
21:
22: printf(“\nInput the second string: “);
23: gets(str2);
24:
25: /* Compare them and display the result. */
26:
27: x = strcmp(str1, str2);

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

Free download pdf