strcmp() in C: Compare Strings

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.

Syntax Top ↑

int result = strcmp(string1, string2);
  • result == 0: the strings are equal.
  • result < 0: string1 compares before string2.
  • result > 0: string1 compares after string2.

Compare Two Strings Top ↑

#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;
}

Case-Sensitive Comparison Top ↑

#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;
}

Compare User Input Top ↑

#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;
}




plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer