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.

Categorystring.h strings
KindLibrary function
Header<string.h>
C standardC89 / C90

📝 Syntax

int strncmp(const char *str1, const char *str2, size_t n);

⚙️ Parameters

str1 RequiredThe first string.
str2 RequiredThe second string.
n RequiredThe 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏