The strncmp() function compares the first n characters of two C-strings—like strcmp(), but with a limit. It is ideal for prefix tests (“does this line start with GET?”), fixed-width record fields, and any time trailing text should be ignored.
01
Compare n
At most n chars.
02
Sign Return
<0 / 0 / >0.
03
Prefix Test
Starts with?
04
vs strcmp
Full vs bounded.
05
Case-Sensitive
Exact letters.
06
<cstring>
C library function.
Fundamentals
Definition and Usage
In C++, strncmp() is declared in <cstring>. It walks both strings in parallel, comparing characters until either a mismatch is found, both strings end within the first n positions, or n comparisons have been performed—whichever comes first.
The return value follows the same rule as strcmp(): zero means the compared portions are equal, a negative value means str1 is less, and a positive value means str1 is greater. Interpret only the sign unless you rely on documented platform behavior.
💡
Beginner Tip
To test whether text starts with "HTTP", use strncmp(text, "HTTP", 4) == 0. Characters after the fourth are ignored, so "HTTP/1.1" matches.
Foundation
📝 Syntax
Function signature and a typical call:
C++
#include <cstring>
int strncmp(const char* str1, const char* str2, size_t n);
// Example:
int r = strncmp("Hello, World!", "Hello, C++!", 5);
// r == 0 (both start with "Hello")
Parameters
str1 — first null-terminated C-string.
str2 — second null-terminated C-string.
n — maximum number of characters to compare.
Return Value
An int indicating lexicographic order of the compared portion: less than 0, equal to 0, or greater than 0.
Cheat Sheet
⚡ Quick Reference
Check
Code pattern
Meaning
Prefix match
strncmp(s, "GET", 3) == 0
Starts with GET
Equal first n
strncmp(a, b, n) == 0
First n chars match
Less than
strncmp(a, b, n) < 0
a sorts before b
Full string
strcmp(a, b)
No length limit
Compare
strncmp(a, b, n)
Bounded compare
Equal?
... == 0
Match in range
Prefix
n = strlen(prefix)
Prefix length
Include
#include <cstring>
Header file
Hands-On
Examples Gallery
Compile with g++ strncmp.cpp -std=c++17 -o strncmp. Each example interprets the return sign the same way as strcmp().
📚 Getting Started
Compare the opening characters of two strings with a limit.
Example 1 — Equal First Five Characters
Compare the start of "Hello, World!" and "Hello, C++!" with n = 5.
C++
#include <iostream>
#include <cstring>
int main() {
const char* str1 = "Hello, World!";
const char* str2 = "Hello, C++!";
int result = std::strncmp(str1, str2, 5);
if (result == 0) {
std::cout << "First 5 characters match.\n";
} else if (result < 0) {
std::cout << "str1 is less in the first 5 chars.\n";
} else {
std::cout << "str1 is greater in the first 5 chars.\n";
}
return 0;
}
📤 Output:
First 5 characters match.
How It Works
Both strings share Hello. The comma and everything after position 5 is not compared, so the result is 0 even though the full strings differ.
Example 2 — Prefix Check for HTTP
Test whether a request line starts with a known verb or scheme.
record1 vs record2 (8): false
record1 vs record3 (8): true
How It Works
Within eight characters, record1 matches the padded start of record3. Mario vs Maria differs at the fifth letter.
Applications
🚀 Common Use Cases
Prefix / starts-with checks — commands, URLs, file extensions at a path start.
Fixed-width records — compare name or ID columns of known width.
Protocol parsing — match HTTP methods, MIME types, or magic bytes as text.
Version string segments — compare major.minor portion only (with care).
Sorting with a limit — order strings by their first n characters.
🧠 How strncmp() Works
1
Initialize counter
Set compared count to zero and read first bytes of both strings.
Start
2
Compare pair
If bytes differ, return their difference sign. If either is '\0', treat missing as zero.
Compare
3
Increment until n
Advance pointers and repeat until n pairs match or a difference appears.
Loop
=
📊
Return sign
Zero if all compared characters match; otherwise negative or positive order.
Important
📝 Notes
Comparison is case-sensitive and uses unsigned char values (like strcmp).
If one string ends before n characters, missing characters are treated as '\0'.
When n == 0, the function returns 0 without reading either string.
Do not compare C-strings with == on pointers—use strncmp or strcmp on contents.
For full semantic version ordering, dedicated parsing beats naive strncmp.
Performance
⚡ Optimization
Limiting n can stop early when strings differ near the start, but worst-case cost is still O(n). For repeated prefix checks on the same prefix, cache strlen(prefix). In modern C++, std::string::compare(0, n, other, 0, n) offers similar behavior with clearer intent.
Wrap Up
Conclusion
strncmp() compares at most n characters of two C-strings with the same return sign as strcmp(). Use it for prefixes and bounded fields; use strcmp() when the entire string must match.
Next, learn strncpy() to copy at most n characters into a buffer—the bounded counterpart to strcpy().
Use strncmp(a, b, n) == 0 for prefix or segment equality
Set n = strlen(prefix) for starts-with helpers
Interpret only the sign of non-zero results
Prefer std::string::compare in new C++ code
Include <cstring> and use std::strncmp
❌ Don’t
Assume non-zero results are exactly 1 or -1
Use strncmp when the full string must match—use strcmp
Compare pointers with == instead of string content
Pass non-null-terminated buffers
Rely on strncmp alone for semantic version logic
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about strncmp()
Use these points for bounded C-string comparison.
5
Core concepts
📊01
At Most n
Bounded compare.
Basics
🔢02
Sign Return
Like strcmp.
Return
🔎03
Prefix
Starts with test.
Pattern
🔄04
vs strcmp
Full vs partial.
Compare
📝05
Case-Sensitive
Exact bytes.
Rule
❓ Frequently Asked Questions
strncmp() compares at most n characters of two null-terminated C-strings lexicographically. It returns an int less than, equal to, or greater than zero if the compared portion of str1 is less than, equal to, or greater than that of str2.
int strncmp(const char* str1, const char* str2, size_t n); Include <cstring>. n limits how many character pairs are examined from the start of each string.
Same convention as strcmp: 0 if the first n characters match (or both strings end within n), less than 0 if str1 sorts before str2 in the compared range, greater than 0 if str1 sorts after. Only the sign is portable.
strcmp() compares until a mismatch or the end of either string. strncmp() stops after n character comparisons—even if longer text differs later. Use strncmp for prefix checks and fixed-width fields.
strncmp returns 0 immediately—no characters are compared. This is rarely useful but defined by the standard.
Yes. "Hello" and "hello" differ at the first character. For case-insensitive bounded compare, use platform helpers (e.g. _strnicmp on Windows, strncasecmp on POSIX) or normalize case first.
Did you know?
The old reference page for strncmp accidentally copied strncat meta descriptions. They are different functions: strncatappends text; strncmpcompares text up to a limit.