strcmp() Function
The strcmp()
function in C is used to compare two strings by evaluating each character sequentially until a difference is encountered or the end of the strings is reached. It performs a binary comparison and returns an integral value that reflects the lexicographical relationship between the two strings.
Syntax of strcmp()
int strcmp(const char *str1, const char *str2);
Parameters
Parameter | Description |
---|---|
str1 | C string to be compared. |
str2 | C string to be compared. |
The function compares the strings character by character, stopping when a difference is found or when a null-character is encountered. It performs a binary comparison, meaning that the numerical values of the characters are used. For locale-specific comparisons, consider using strcoll()
.
Examples for strcmp()
Example 1: Comparing Identical Strings
This example demonstrates how strcmp()
returns 0 when comparing two identical strings.
Program
#include <stdio.h>
#include <string.h>
int main() {
const char *s1 = "Hello";
const char *s2 = "Hello";
int result = strcmp(s1, s2);
printf("Result: %d\n", result);
return 0;
}
Explanation:
- Two identical strings are defined.
- The
strcmp()
function compares them character by character. - Since both strings are identical, the function returns
0
. - The output confirms that the strings are equal.
Output:
Result: 0
Example 2: Comparing Different Strings (Negative Result)
This example shows how strcmp()
returns a negative value when the first non-matching character in the first string has a lower value than in the second string.
Program
#include <stdio.h>
#include <string.h>
int main() {
const char *s1 = "abc";
const char *s2 = "abd";
int result = strcmp(s1, s2);
printf("Result: %d\n", result);
return 0;
}
Explanation:
- The first string is “abc” and the second is “abd”.
- The comparison proceeds until the third character where ‘c’ is less than ‘d’.
- The function returns a negative value to indicate that the first string is lexicographically smaller.
- The result is printed accordingly.
Output:
Result: -1
Example 3: Comparing Different Strings (Positive Result)
This example demonstrates how strcmp()
returns a positive value when the first string is lexicographically greater than the second string.
Program
#include <stdio.h>
#include <string.h>
int main() {
const char *s1 = "world";
const char *s2 = "hello";
int result = strcmp(s1, s2);
printf("Result: %d\n", result);
return 0;
}
Explanation:
- The first string is “world” and the second string is “hello”.
- The comparison finds that the first character of “world” (‘w’) is greater than that of “hello” (‘h’).
- The function returns a positive value to indicate that the first string is lexicographically greater.
- The output displays the resulting positive value.
Output:
Result: 15