In C, strncmp() compares two C-strings like strcmp(), but it stops after n characters or at a '\0'. Letter case still matters.
You pass both strings and the count. All three are required. A result of 0 means only the compared part matches, not always the whole strings. Include <string.h>.
Syntax
Pass both strings and the count. Start with this call.
C
strncmp("Hello", "Help!", 3);
Call
What it does
strncmp("Hello", "Help!", 3)
Compares only the first 3 characters. Here that prefix matches.
Include <string.h>. Only the sign of the result is portable.
Library declarations
C
int strncmp(const char *s1, const char *s2, size_t n);
Parameters
Parameter
Description
first
Required. The first string.
second
Required. The second string.
count
Required. The most characters to compare.
Return Value
Return Value
Description
0
The compared part matches.
Less than 0
The first string comes first in the compared part.
Greater than 0
The first string comes after in the compared part.
C Examples
Example 1 — Equal Within n
Two strings can differ later and still compare equal for a small n.
C
#include <stdio.h>
#include <string.h>
int main(void) {
int r = strncmp("Hello", "Help!", 3);
if (r == 0) {
printf("equal within n\n");
} else {
printf("different\n");
}
return 0;
}
Output
equal within n
How It Works
Limit to 3. Only H, e, l are compared.
All three match. Return value is 0.
Later difference ignored. Index 3 is l vs p, but n already stopped.
Not full equality. Use strcmp when the whole string must match.
Example 2 — Prefix Check
A common pattern: test whether a string starts with a fixed prefix.