0
0
CHow-ToBeginner · 3 min read

How to Compare Strings in C: Syntax and Examples

In C, you compare strings using the strcmp function from string.h. It returns 0 if the strings are equal, a negative number if the first string is less, and a positive number if it is greater.
📐

Syntax

The strcmp function compares two strings character by character.

  • str1: first string to compare
  • str2: second string to compare
  • Returns 0 if both strings are equal
  • Returns < 0 if str1 is less than str2
  • Returns > 0 if str1 is greater than str2
c
int strcmp(const char *str1, const char *str2);
💻

Example

This example shows how to compare two strings and print if they are equal or which one is greater.

c
#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "apple";
    char str2[] = "banana";

    int result = strcmp(str1, str2);

    if (result == 0) {
        printf("Strings are equal.\n");
    } else if (result < 0) {
        printf("'%s' is less than '%s'.\n", str1, str2);
    } else {
        printf("'%s' is greater than '%s'.\n", str1, str2);
    }

    return 0;
}
Output
'apple' is less than 'banana'.
⚠️

Common Pitfalls

Many beginners try to compare strings using ==, which only compares memory addresses, not string content.

Always use strcmp to compare the actual text.

c
#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "hello";
    char str2[] = "hello";

    // Wrong way: compares addresses, not content
    if (str1 == str2) {
        printf("Strings are equal (wrong check).\n");
    } else {
        printf("Strings are NOT equal (wrong check).\n");
    }

    // Right way: compares content
    if (strcmp(str1, str2) == 0) {
        printf("Strings are equal (correct check).\n");
    } else {
        printf("Strings are NOT equal (correct check).\n");
    }

    return 0;
}
Output
Strings are NOT equal (wrong check). Strings are equal (correct check).
📊

Quick Reference

FunctionPurposeReturn Value
strcmp(str1, str2)Compare two strings0 if equal, <0 if str1 < str2, >0 if str1 > str2
strncmp(str1, str2, n)Compare first n charactersSame as strcmp but limited to n chars
strcasecmp(str1, str2)Compare ignoring case (POSIX)0 if equal ignoring case

Key Takeaways

Use strcmp from string.h to compare string contents in C.
strcmp returns 0 when strings are exactly equal.
Never use == to compare strings; it compares addresses, not text.
Check strcmp result to know if one string is less or greater.
For partial or case-insensitive comparison, use strncmp or strcasecmp.