8.9 String Comparison
Since the C programming language does not define a built-in data type for strings, no operators are defined for use with strings. Instead, you must use the string functions defined in the standard library. For example, in Python, you could determine if two strings were identical using the == operator, but this can not be done in C.
The strcmp function is used to compare whether two strings are identical or to determine their relative lexicographical ordering. In Python, this could be done using the regular relational operators (==, <, >, etc).
|
The String Comparison Function
string.h
int strcmp(char str1[], char str2[]);
The function takes two strings and compares them lexicographically to determine their relative ordering or whether they are identical. The integer value returned indicates the result of the comparison:
|
Testing for Equality
Suppose the string array name has been declared and initialized. We can use the strcmp function to determine if the array contains the name "Smith":
- if(strcmp(name, "Smith") == 0)
- printf("The strings are the same.\n");
- else
- printf("The strings are not the same.\n");
Two strings are identical if they contain the exact same number of elements and the characters in corresponding elements are identical. Suppose name contains the string
when it is compared against the literal string "Smith", the strcmp function will return 0 indicating the strings are identical.
Now suppose name contains "smith", what would the function return?
Since the characters in the first position of the two arrays are not equal, the two strings are not idential. Remember, the character 's' is not identical to the character 'S'. They have different ASCII code values: the code of 'S' is 83 and the code for 's' is 115. In this case, the function will return a positive integer value since the string "smith" follows the string "Smith" in relative order.
Testing Relative Order
Consider the string declarations
- char name1[20] = "Mary";
- char name2[20] = "Maria";
which result in the character arrays
Suppose we want to determine if the string in name1 precedes the string in name2. We will again need to use the strcmp function and compare the result against 0:
- if(strcmp(name1, name2) < 0)
- printf("The string '%s' precedes the string '%s'.\n", name1, name2);
- else
- printf("The string '%s' precedes the string '%s'.\n", name2, name1);
Likewise, if you want to determine whether the string in the first argument to strcmp follows the second, you would test if the result is greater than 0:
- if(strcmp("xyz", "abc") > 0) {
- printf("xyz follows abc alphabetically.\n");
- }
Consider the two strings
what value is assigned to variable
To determine this, we need to compare the two strings the way the Examining the characters at that position, we quickly see that |