strncmp() Compare at most n characters of two strings
strncmp() Compare at most n characters of two strings
strncmp() compares at most n characters as unsigned chars, stopping at a difference or null. Zero means compared parts match; n == 0 returns zero.
| Category | string.h strings |
|---|---|
| Kind | Library function |
| Header | <string.h> |
| C standard | C89 / C90 |
📝 Syntax
int strncmp(const char *str1, const char *str2, size_t n);
⚙️ Parameters
| str1 Required | The first string. |
|---|---|
| str2 Required | The second string. |
| n Required | The maximum number of characters to compare. |
Returns: Returns negative, zero, or positive according to the compared portions of str1 and str2; returns zero when n is zero.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
First 4 characters match
⚠️ Warning A zero result means only that the compared portions match, not necessarily that the complete strings are identical.
💡 Tip As with strcmp(), rely only on the sign of the result, not its exact magnitude.
🏷️ Related string.h functions
📚 Related Tutorials
❓ FAQ
QDoes strncmp returning zero mean the strings are completely equal?
ANot necessarily. If only four characters are compared, later characters may differ. For complete equality, account for length or use strcmp.
QWhat happens when strncmp is called with n equal to zero?
AIt compares no characters and returns zero. The pointer arguments should still satisfy the function's validity requirements.
QHow can I use strncmp to test whether a string starts with a given prefix?
ACompare the first strlen(prefix) characters; a result of 0 means the prefix matches, as in strncmp(str, prefix, strlen(prefix)) == 0. Both arguments must be valid strings. This test is case-sensitive and does not require str to end immediately after the prefix; use a separate comparison for complete equality.