C strcmp() Function
The strcmp()
function in C is used to compare two strings. It compares each character of the strings and returns a value based on the result of the comparison. The function is defined in the string.h
library.
Syntax of strcmp()
The syntax of the strcmp()
function is as follows:
Syntax:
int strcmp(const char *str1, const char *str2);
The function takes two arguments:
- str1: A pointer to the first string to be compared.
- str2: A pointer to the second string to be compared.
The function returns:
- A value < 0 if
str1
is less thanstr2
. - A value > 0 if
str1
is greater thanstr2
. - 0 if both strings are equal.
Example of strcmp() Function
Here is an example that demonstrates how the strcmp()
function works:
Example:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "Hello";
char str2[] = "World";
char str3[] = "Hello";
int result1 = strcmp(str1, str2); // Comparing "Hello" with "World"
int result2 = strcmp(str1, str3); // Comparing "Hello" with "Hello"
// Output the results of comparisons
printf("Comparison Result 1: %d\n", result1); // Output will be negative
printf("Comparison Result 2: %d\n", result2); // Output will be 0
return 0;
}
Output:
Comparison Result 1: -1
Comparison Result 2: 0
Comparison Result 2: 0
Explanation of the Example
In this example:
strcmp(str1, str2)
compares the strings "Hello" and "World". Since "Hello" comes before "World" lexicographically, the function returns a negative value (e.g., -1).strcmp(str1, str3)
compares the strings "Hello" and "Hello". Since the strings are identical, the function returns 0.
Important Notes
- The
strcmp()
function is case-sensitive. This means that uppercase and lowercase characters are treated as different (e.g., 'A' < 'a'). - It's essential to ensure that the strings being compared are properly null-terminated, as the function relies on the null character '0' to determine the end of the string.
- The comparison is done lexicographically (like dictionary order), which means that the function compares the ASCII values of corresponding characters in the strings.