strncmp() in C
Safe string comparison function
What is strncmp()?
Definition: strncmp() is a C standard library function that compares up to n
characters of two strings. It's defined in
<string.h> and provides safer
string comparison than strcmp() by limiting the number of characters compared.
Function Prototype
#include <string.h>
int strncmp(const char *str1, const char *str2, size_t n);
Parameters
- str1 - Pointer to the first string to compare
- str2 - Pointer to the second string to compare
- n - Maximum number of characters to compare
Return Value
| Return Value | Meaning |
|---|---|
| < 0 | str1 is less than str2 |
| 0 | str1 is equal to str2 (first n characters) |
| > 0 | str1 is greater than str2 |
Basic Usage
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello World";
char str2[] = "Hello";
// Compare first 5 characters
int result = strncmp(str1, str2, 5);
if (result == 0) {
printf("First 5 characters are equal\n");
} else if (result < 0) {
printf("str1 < str2\n");
} else {
printf("str1 > str2\n");
}
return 0;
}
// Output: First 5 characters are equalstrncmp() vs strcmp()
| Feature | strcmp() | strncmp() |
|---|---|---|
| Comparison Length | Entire string | Up to n characters |
| Safety | Less safe | Safer (bounded) |
| Use Case | Full string comparison | Partial comparison, prefix matching |
| Parameters | 2 (str1, str2) | 3 (str1, str2, n) |
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello World";
char str2[] = "Hello";
// strcmp compares entire strings
printf("strcmp: %d\n", strcmp(str1, str2)); // Not equal
// strncmp compares first 5 characters
printf("strncmp: %d\n", strncmp(str1, str2, 5)); // Equal (0)
return 0;
}Practical Examples
Example 1: Prefix Matching
#include <stdio.h>
#include <string.h>
int main() {
char command[] = "print hello";
// Check if command starts with "print"
if (strncmp(command, "print", 5) == 0) {
printf("Print command detected\n");
}
// Check if command starts with "exit"
if (strncmp(command, "exit", 4) == 0) {
printf("Exit command detected\n");
}
return 0;
}Example 2: Case-Insensitive Comparison (with strncasecmp)
#include <stdio.h>
#include <string.h>
#include <strings.h> // For strncasecmp
int main() {
char str1[] = "Hello";
char str2[] = "HELLO";
// Case-sensitive comparison
printf("strncmp: %d\n", strncmp(str1, str2, 5));
// Case-insensitive comparison (POSIX)
printf("strncasecmp: %d\n", strncasecmp(str1, str2, 5));
return 0;
}Example 3: Validating File Extensions
#include <stdio.h>
#include <string.h>
int is_text_file(const char *filename) {
size_t len = strlen(filename);
if (len < 4) return 0;
// Check last 4 characters for ".txt"
return strncmp(filename + len - 4, ".txt", 4) == 0;
}
int main() {
printf("%d\n", is_text_file("document.txt")); // 1 (true)
printf("%d\n", is_text_file("image.png")); // 0 (false)
return 0;
}Example 4: Comparing Array of Strings
#include <stdio.h>
#include <string.h>
int main() {
char *keywords[] = {"if", "else", "while", "for"};
char token[] = "while";
int found = 0;
for (int i = 0; i < 4; i++) {
if (strncmp(token, keywords[i], strlen(keywords[i])) == 0) {
printf("Found keyword: %s\n", keywords[i]);
found = 1;
break;
}
}
if (!found) {
printf("Not a keyword\n");
}
return 0;
}Common Pitfalls
Pitfall 1: Comparing More Than String Length
char str1[] = "Hi"; // Length 2
char str2[] = "Hello";
// Comparing 10 characters when str1 only has 2
// This compares beyond the string (undefined behavior)
int result = strncmp(str1, str2, 10); // DANGEROUS!
// BETTER: Use the shorter length
size_t len = strlen(str1) < strlen(str2) ? strlen(str1) : strlen(str2);
result = strncmp(str1, str2, len);
Pitfall 2: Off-by-One Errors
char str1[] = "test";
char str2[] = "test";
// Comparing 3 characters: "tes" == "tes"
strncmp(str1, str2, 3); // Returns 0 (equal)
// To compare entire string including null terminator
strncmp(str1, str2, 5); // Compares "test\0"
Pitfall 3: NULL Pointer
char *str1 = NULL;
char str2[] = "test";
// CRASH! Always check for NULL
// strncmp(str1, str2, 4); // UNDEFINED BEHAVIOR
// SAFE version
if (str1 != NULL && str2 != NULL) {
strncmp(str1, str2, 4);
}Related Functions
| Function | Description | Use Case |
|---|---|---|
| strcmp() | Compare entire strings | Full string equality |
| strncmp() | Compare n characters | Prefix matching, partial comparison |
| strcasecmp() | Case-insensitive comparison | Ignore case differences |
| strncasecmp() | Case-insensitive n chars | Prefix matching, ignore case |
| memcmp() | Compare memory blocks | Binary data comparison |
Best Practices
Recommendations:
- Always check for NULL pointers before calling strncmp()
- Use strncmp() instead of strcmp() for safer code
- Ensure n doesn't exceed the length of shorter string
- Use
strlen()to determine safe comparison length - For case-insensitive comparison, use strncasecmp() (POSIX)
- Check return value with ==, <, or > operators
- Don't rely on specific return values (just sign matters)
Key Takeaways
Remember:
- strncmp() compares up to n characters of two strings
- Returns 0 if equal, <0 if str1 < str2, >0 if str1 > str2
- Safer than strcmp() due to bounded comparison
- Perfect for prefix matching and partial comparisons
- Always validate n against actual string lengths
- Check for NULL pointers before calling
- Defined in
<string.h>