Comparing strings with strcmp
What you'll learn: How to use the strcmp function to determine if two strings are identical or which one comes first alphabetically.
The "Double Equals" Trap
In C, you might be tempted to compare two strings using if (string1 == string2). However, this won't work the way you expect. Because strings are actually arrays, using == only checks if the two strings are stored at the exact same memory address. It doesn't look at the characters inside the boxes. To actually read the text and compare it, we need a special tool from the <string.h> library called strcmp (short for "string comparison").
How strcmp Works
Think of strcmp like a judge in a dictionary contest. It compares two strings character by character until it finds a difference or reaches the end.
The function returns an integer, and the result can be a bit counter-intuitive at first:
- 0: The strings are perfectly equal.
- A non-zero value: The strings are different.
Code Example
To use it, you must include the header file and check if the result is equal to zero.
#include <stdio.h>
#include <string.h>
int main() {
char secretPassword[] = "apple123";
char userInput[] = "apple123";
// strcmp returns 0 if they match
if (strcmp(secretPassword, userInput) == 0) {
printf("Access granted!\n");
} else {
printf("Access denied!\n");
}
return 0;
}
Behind the Scenes
strcmp subtracts the ASCII values of the characters. If it compares "Apple" and "Apply", it sees the first four letters are the same. When it hits 'e' vs 'y', it sees they aren't the same and stops.
One important note: strcmp is case-sensitive. To the computer, "Apple" and "apple" are completely different because capital 'A' and lowercase 'a' have different numeric codes. If you need a perfect match, every single character, including capitalization, must be identical.
Key takeaway
Always use strcmp(str1, str2) == 0 to check if two strings are equal; never use ==.