Comparing strings with C
Categories:
Mastering String Comparison in C: A Comprehensive Guide

Learn the essential techniques for comparing strings in C, including standard library functions, manual comparison, and best practices for robust code.
Comparing strings is a fundamental operation in C programming, crucial for tasks like user authentication, data validation, sorting, and searching. Unlike many higher-level languages where strings are first-class citizens, C treats strings as arrays of characters terminated by a null character (\0
). This distinction means you cannot simply use the ==
operator to compare string contents; doing so would only compare their memory addresses, not their actual values. This article will guide you through the correct and efficient ways to compare strings in C, covering standard library functions and manual implementations.
The strcmp()
Function: Your Primary Tool
The strcmp()
function, part of the <string.h>
library, is the most common and recommended way to compare two strings in C. It performs a lexicographical comparison, meaning it compares strings character by character based on their ASCII values until a difference is found or the end of both strings is reached. The function returns an integer value indicating the relationship between the two strings.
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "apple";
char str3[] = "banana";
char str4[] = "apricot";
// Compare str1 and str2 (identical)
int result1 = strcmp(str1, str2);
if (result1 == 0) {
printf("\"%s\" and \"%s\" are equal.\n", str1, str2);
} else {
printf("\"%s\" and \"%s\" are not equal. Result: %d\n", str1, str2, result1);
}
// Compare str1 and str3 (str1 < str3)
int result2 = strcmp(str1, str3);
if (result2 < 0) {
printf("\"%s\" comes before \"%s\". Result: %d\n", str1, str3, result2);
} else if (result2 > 0) {
printf("\"%s\" comes after \"%s\". Result: %d\n", str1, str3, result2);
}
// Compare str3 and str1 (str3 > str1)
int result3 = strcmp(str3, str1);
if (result3 < 0) {
printf("\"%s\" comes before \"%s\". Result: %d\n", str3, str1, result3);
} else if (result3 > 0) {
printf("\"%s\" comes after \"%s\". Result: %d\n", str3, str1, result3);
}
// Compare str1 and str4 (str1 > str4 due to 'p' vs 'r')
int result4 = strcmp(str1, str4);
if (result4 < 0) {
printf("\"%s\" comes before \"%s\". Result: %d\n", str1, str4, result4);
} else if (result4 > 0) {
printf("\"%s\" comes after \"%s\". Result: %d\n", str1, str4, result4);
}
return 0;
}
Example usage of strcmp()
demonstrating different return values.
strcmp()
is case-sensitive. "Apple" and "apple" will be considered different. For case-insensitive comparison, you might need to convert strings to a common case (e.g., all lowercase) before comparing, or use functions like strcasecmp()
(available on some systems, but not standard C).flowchart TD A[Start String Comparison] --> B{Call strcmp(s1, s2)} B --> C{Result == 0?} C -- Yes --> D[Strings are Equal] C -- No --> E{Result < 0?} E -- Yes --> F[s1 comes before s2] E -- No --> G[s1 comes after s2] D & F & G --> H[End Comparison]
Flowchart illustrating the logic of the strcmp()
function.
Comparing a Specific Number of Characters with strncmp()
Sometimes, you only need to compare a prefix of two strings or ensure you don't read past the bounds of a buffer. For these scenarios, the strncmp()
function is ideal. It works similarly to strcmp()
but takes an additional argument n
, which specifies the maximum number of characters to compare. This is particularly useful when dealing with fixed-size buffers or parsing data with known prefixes.
#include <stdio.h>
#include <string.h>
int main() {
char password_input[] = "P@ssw0rd123";
char stored_prefix[] = "P@ssw0rd";
char another_string[] = "P@ssw0rd_test";
// Compare first 8 characters of password_input and stored_prefix
if (strncmp(password_input, stored_prefix, 8) == 0) {
printf("First 8 characters of \"%s\" and \"%s\" are equal.\n", password_input, stored_prefix);
} else {
printf("First 8 characters are different.\n");
}
// Compare first 8 characters of password_input and another_string
if (strncmp(password_input, another_string, 8) == 0) {
printf("First 8 characters of \"%s\" and \"%s\" are equal.\n", password_input, another_string);
} else {
printf("First 8 characters are different.\n");
}
// Compare full strings for context
if (strcmp(password_input, another_string) == 0) {
printf("Full strings are equal.\n");
} else {
printf("Full strings are different.\n");
}
return 0;
}
Using strncmp()
to compare a limited number of characters.
strncmp()
if one string is shorter than n
characters and the other is longer but matches up to the shorter string's length. strncmp()
will return 0 if the first n
characters match, even if the strings are of different lengths. Always consider both length and content if exact string equality is required.Manual String Comparison
While strcmp()
and strncmp()
are highly optimized and generally preferred, understanding how to implement string comparison manually can deepen your understanding of C strings. A manual comparison involves iterating through both strings character by character until a mismatch is found or the null terminator of either string is reached. If both strings reach their null terminators simultaneously, they are equal.
#include <stdio.h>
int my_strcmp(const char *s1, const char *s2) {
while (*s1 != '\0' && *s1 == *s2) {
s1++;
s2++;
}
// Return the difference of the ASCII values of the first differing characters,
// or 0 if both strings ended simultaneously.
return (unsigned char)*s1 - (unsigned char)*s2;
}
int main() {
char str1[] = "hello";
char str2[] = "hello";
char str3[] = "world";
char str4[] = "hell";
printf("my_strcmp(\"%s\", \"%s\") = %d\n", str1, str2, my_strcmp(str1, str2)); // Expected: 0
printf("my_strcmp(\"%s\", \"%s\") = %d\n", str1, str3, my_strcmp(str1, str3)); // Expected: < 0
printf("my_strcmp(\"%s\", \"%s\") = %d\n", str3, str1, my_strcmp(str3, str1)); // Expected: > 0
printf("my_strcmp(\"%s\", \"%s\") = %d\n", str1, str4, my_strcmp(str1, str4)); // Expected: > 0
return 0;
}
A custom implementation of strcmp()
.
const char *
for input strings if the function doesn't modify them. This indicates to the compiler and other developers that the string contents are read-only, improving code safety and clarity.