In C, comparing two strings isn’t as simple as using the equality operator (==). This operator compares memory addresses, not the actual string content. To accurately compare strings, you need the strcmp()
function from the string.h
library. This function performs a lexicographical comparison, meaning it compares strings character by character based on their ASCII values.
Understanding strcmp()
The strcmp()
function takes two strings as arguments:
int strcmp(const char *s1, const char *s2);
s1
: The first string to compare.s2
: The second string to compare.
The function returns an integer value indicating the relationship between the two strings:
- 0: If the strings are identical (
s1
==s2
). - Less than 0: If
s1
is lexicographically less thans2
(comes befores2
in dictionary order). - Greater than 0: If
s1
is lexicographically greater thans2
(comes afters2
in dictionary order).
How strcmp() Works
strcmp()
compares the strings character by character until:
- A mismatch is found: If the ASCII values of corresponding characters differ, the function returns the difference between those values. A positive difference indicates
s1
is greater, and a negative difference indicatess1
is less thans2
. - The end of one string is reached: If one string is shorter than the other and all preceding characters are equal, the shorter string is considered less than the longer string. This is because the shorter string is followed by a null terminator (”), which has an ASCII value of 0, while the longer string continues with other characters.
- Both strings reach the null terminator simultaneously: This indicates the strings are identical, and the function returns 0.
Examples of strcmp() in Action
Let’s illustrate with examples:
1. Comparing Identical Strings:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "hello";
int result = strcmp(str1, str2);
printf("Comparison result: %dn", result); // Output: 0
return 0;
}
2. Comparing Strings with Different Case:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "hello";
int result = strcmp(str1, str2);
printf("Comparison result: %dn", result); // Output: A negative value (e.g., -32)
return 0;
}
3. Comparing Strings of Different Lengths:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "applesauce";
int result = strcmp(str1, str2);
printf("Comparison result: %dn", result); // Output: A negative value
return 0;
}
Conclusion
The strcmp()
function is essential for string comparisons in C. Understanding its lexicographical comparison mechanism and return values is crucial for writing correct and efficient C code. By using strcmp()
, you can accurately determine the relationship between two strings, enabling tasks like sorting, searching, and data validation.