Course contentsShow
← C
Lesson 850 of 1,21912. The Standard LibraryFree lesson

Lexicographical comparison with `strcmp`

Lexicographical comparison with strcmp

What you'll learn: How to determine if two strings are identical or which one comes first alphabetically using the strcmp function.

The Alphabetical Scale

In C, you cannot compare two strings using the == operator. Because strings are actually arrays, == would mistakenly check if they are stored at the same memory address rather than checking their contents. To see if "apple" matches "apple," we use a process called lexicographical comparison via the strcmp (string compare) function.

Think of strcmp as a librarian. If you give the librarian two words, they will tell you if the words are the same, or which one appears first in the dictionary.

How strcmp Works

The function compares strings character by character based on their ASCII values. It continues until it finds a difference or hits the null terminator (\0).

When you call strcmp(string1, string2), it returns an integer:

  • 0: The strings are identical.
  • A negative value: string1 comes before string2 (e.g., "apple" vs "banana").
  • A positive value: string1 comes after string2 (e.g., "cherry" vs "banana").

Coding the Comparison

To use strcmp, you must include <string.h>. It is common practice to compare the result against zero to drive your program's logic.

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

int main() {
    char pass[] = "secret";
    char input[] = "secret";

    // strcmp returns 0 if they match perfectly
    if (strcmp(pass, input) == 0) {
        printf("Access granted!\n");
    } else {
        printf("Access denied.\n");
    }

    // Checking alphabetical order
    char a[] = "Apple";
    char b[] = "Banana";

    if (strcmp(a, b) < 0) {
        printf("%s comes before %s", a, b);
    }

    return 0;
}

Case Sensitivity Matters

It is important to remember that strcmp is case-sensitive. In the ASCII table, uppercase letters have lower numerical values than lowercase letters. This means "Zebra" will actually be considered "less than" (coming before) "apple" because 'Z' (90) is smaller than 'a' (97). When using strcmp, always ensure your strings are in a consistent case if you want standard dictionary results.

Key takeaway

Use strcmp(s1, s2) == 0 to check for equality, as it returns zero when strings are identical.