C++ String strncmp() Function

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
Bounded compare

What You’ll Learn

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.

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.

📝 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.

⚡ Quick Reference

CheckCode patternMeaning
Prefix matchstrncmp(s, "GET", 3) == 0Starts with GET
Equal first nstrncmp(a, b, n) == 0First n chars match
Less thanstrncmp(a, b, n) < 0a sorts before b
Full stringstrcmp(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

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;
}

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.

C++
#include <iostream>
#include <cstring>

bool startsWith(const char* text, const char* prefix) {
    return std::strncmp(text, prefix, std::strlen(prefix)) == 0;
}

int main() {
    const char* line1 = "GET /index.html HTTP/1.1";
    const char* line2 = "POST /submit HTTP/1.1";

    std::cout << std::boolalpha;
    std::cout << "line1 is GET?  " << startsWith(line1, "GET") << "\n";
    std::cout << "line2 is GET?  " << startsWith(line2, "GET") << "\n";
    std::cout << "line1 is HTTP? " << startsWith(line1, "HTTP") << "\n";

    return 0;
}

How It Works

strncmp with n = strlen(prefix) is a classic prefix test. line1 begins with GET but not with HTTP at position 0.

📈 Practical Patterns

Contrast with full compare, detect ordering, and read fixed-width data.

Example 3 — strncmp() vs strcmp()

Same strings can match with a limit but differ on a full compare.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* a = "version-1.2.3";
    const char* b = "version-1.9.0";

    int limited = std::strncmp(a, b, 9);  // "version-1"
    int full    = std::strcmp(a, b);

    std::cout << "strncmp(9): " << limited << " (0 = equal prefix)\n";
    std::cout << "strcmp():   " << full << " (<0 means a before b)\n";

    return 0;
}

How It Works

The first nine characters version-1 match, but full strings diverge at 2 vs 9. Use strncmp only when trailing text should be ignored.

Example 4 — Detect Less or Greater

Compare product codes lexicographically within the first four characters.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* codeA = "ABX-100";
    const char* codeB = "ABY-050";

    int cmp = std::strncmp(codeA, codeB, 4);

    if (cmp < 0) {
        std::cout << "codeA comes before codeB (first 4 chars).\n";
    } else if (cmp > 0) {
        std::cout << "codeA comes after codeB (first 4 chars).\n";
    } else {
        std::cout << "First 4 characters are equal.\n";
    }

    return 0;
}

How It Works

At index 2, X (88) is less than Y (89), so strncmp returns negative. Only the sign matters for sorting decisions.

Example 5 — Compare Fixed-Width Name Field

Legacy records may store names padded to exactly eight characters.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* record1 = "Mario   ";
    const char* record2 = "Maria   ";
    const char* record3 = "Mario   extra";

    const std::size_t fieldWidth = 8;

    std::cout << std::boolalpha;
    std::cout << "record1 vs record2 (8): "
              << (std::strncmp(record1, record2, fieldWidth) == 0) << "\n";
    std::cout << "record1 vs record3 (8): "
              << (std::strncmp(record1, record3, fieldWidth) == 0) << "\n";

    return 0;
}

How It Works

Within eight characters, record1 matches the padded start of record3. Mario vs Maria differs at the fifth letter.

🚀 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.

📝 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.

⚡ 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.

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().

💡 Best Practices

✅ Do

  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about strncmp()

Use these points for bounded C-string comparison.

5
Core concepts
🔢 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: strncat appends text; strncmp compares text up to a limit.

Continue the String Functions Series

Compare with limits using strncmp(), then copy with strncpy().

Next: strncpy() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful