strcmp() / strncmp()
Functions that compare two strings in lexicographic (dictionary) order. Use them for equality checks and sort comparison logic. Since strings cannot be compared with the == operator, you must always use these functions instead.
Syntax
// Compares s1 and s2 in lexicographic order. // Returns: negative if s1 < s2, 0 if s1 == s2, positive if s1 > s2. int strcmp(const char *s1, const char *s2); // Compares only the first n bytes. int strncmp(const char *s1, const char *s2, size_t n); // Case-insensitive comparison (POSIX extension, not standard C). int strcasecmp(const char *s1, const char *s2); // Unix-like systems // Case-insensitive comparison on Windows. int _stricmp(const char *s1, const char *s2); // Windows (MSVC)
Return Value
| Return value | Meaning | Example usage |
|---|---|---|
| 0 | The two strings are equal. | Use if (strcmp(a, b) == 0) to check for equality. |
| Negative | s1 comes before s2 in lexicographic order. | Can be used as the return value of a sort comparison function. |
| Positive | s1 comes after s2 in lexicographic order. | Can be used as the return value of a sort comparison function. |
Sample Code
#include <stdio.h>
#include <string.h>
int main(void) {
// Check for equality using strcmp.
const char *s1 = "apple";
const char *s2 = "apple";
const char *s3 = "banana";
if (strcmp(s1, s2) == 0) {
printf("s1 and s2 are equal.\n"); // This line is printed.
}
// Check the ordering relationship.
int cmp = strcmp(s1, s3);
if (cmp < 0) {
printf("%s comes before %s in lexicographic order.\n", s1, s3);
// Prints: "apple comes before banana in lexicographic order."
}
// Use strncmp to compare only the first N characters (e.g., command prefix matching).
const char *cmd = "set_value";
if (strncmp(cmd, "set_", 4) == 0) {
printf("The command starts with set_.\n"); // This line is printed.
}
// Example: sort a string array using strcmp.
const char *fruits[] = {"cherry", "apple", "banana"};
int n = 3;
// Sort using bubble sort.
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (strcmp(fruits[j], fruits[j + 1]) > 0) {
const char *tmp = fruits[j];
fruits[j] = fruits[j + 1];
fruits[j + 1] = tmp;
}
}
}
printf("Sorted: ");
for (int i = 0; i < n; i++) printf("%s ", fruits[i]);
printf("\n"); // Prints: "apple banana cherry"
return 0;
}
Notes
Writing if (s1 == s2) compares pointer addresses, so two strings with the same content but stored at different addresses will evaluate to false. Always use strcmp() to compare string contents.
Comparison is performed on byte values (as unsigned char). This means the result may differ from alphabetical order, and in particular it cannot be used to sort multibyte characters such as Japanese text. Use strcoll() for locale-aware comparisons.
For applying these functions to general-purpose sorting, see also qsort() / bsearch().
If you find any errors or copyright issues, please contact us.