strcmp() compares two null-terminated strings lexicographically and is case-sensitive. The return value is negative, zero or positive; portable code should not assume the result is exactly -1 or 1.
int result = strcmp(string1, string2);
result == 0: the strings are equal.result < 0: string1 compares before string2.result > 0: string1 compares after string2.#include <stdio.h>
#include <string.h>
int main(void) {
char first[] = "apple";
char second[] = "banana";
int result = strcmp(first, second);
if (result == 0) {
printf("The strings are equal.\n");
} else if (result < 0) {
printf("First string comes before second.\n");
} else {
printf("First string comes after second.\n");
}
return 0;
}
#include <stdio.h>
#include <string.h>
int main(void) {
char first[] = "plus2net";
char second[] = "Plus2net";
if (strcmp(first, second) == 0) {
printf("Equal\n");
} else {
printf("Different because comparison is case-sensitive.\n");
}
return 0;
}
#include <stdio.h>
#include <string.h>
int main(void) {
char first[100];
char second[100];
printf("Enter the first string: ");
if (fgets(first, sizeof(first), stdin) == NULL) {
return 1;
}
first[strcspn(first, "\n")] = '\0';
printf("Enter the second string: ");
if (fgets(second, sizeof(second), stdin) == NULL) {
return 1;
}
second[strcspn(second, "\n")] = '\0';
printf("%s\n", strcmp(first, second) == 0 ? "Equal" : "Not equal");
return 0;
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.