C String strncmp() Function

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
<string.h>

What You’ll Learn

The strncmp() function compares at most n characters of two C-strings. It works like strcmp() with a length cap—ideal for prefix checks, protocol headers, and bounded comparisons where you do not need to scan the entire string.

01

Bounded

Max n bytes.

02

0 = match

Within n.

03

Prefix

Start check.

04

Sign matters

<0 or >0.

05

string.h

Standard C.

06

vs strcmp

Full compare.

Definition and Usage

strncmp stands for string n compare. It walks both strings byte by byte, comparing up to n characters. It stops early if a mismatch is found or if a null terminator is reached in either string before n comparisons are done.

A return value of 0 means the compared portion is equal—not necessarily that the entire strings match. For example, strncmp("apple", "application", 5) == 0 even though strcmp would report a difference.

💡
Beginner Tip

After a prefix check with strncmp, call strcmp or compare lengths if you need full equality. strncmp(a, b, n) == 0 only guarantees the first n bytes (or up to the shorter string’s end) match.

📝 Syntax

Standard C declaration:

C
int strncmp(const char *s1, const char *s2, size_t n);

Parameters

  • s1 — first null-terminated string.
  • s2 — second null-terminated string.
  • n — maximum number of bytes to compare.

Return Value

  • < 0 if the compared portion of s1 is less than s2.
  • 0 if the compared portions are equal.
  • > 0 if the compared portion of s1 is greater than s2.
  • Only the sign is guaranteed for ordering—not the exact integer magnitude.

Header

  • #include <string.h>

⚡ Quick Reference

s1s2nResult
"Hello, World!""Hello, C!"70 (both start with "Hello, ")
"apple""application"50 (prefix match)
"cat""dog"3< 0 ('c' < 'd')
"anything""other"00 (nothing compared)
Prefix
strncmp(s1, s2, n) == 0

First n match

Full equal
strcmp(s1, s2) == 0

Entire string

HTTP verb
strncmp(line, "GET ", 4)

Method check

Like memcmp
memcmp(s1, s2, n)

Fixed n bytes

Examples Gallery

Compile with gcc strncmp.c -std=c11 -o strncmp. Each example shows a different way to interpret the return value.

📚 Getting Started

Compare only the first few characters of two strings.

Example 1 — Compare the First 7 Characters

Check whether "Hello, World!" and "Hello, C!" share the same opening.

C
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *str1 = "Hello, World!";
    const char *str2 = "Hello, C!";

    int result = strncmp(str1, str2, 7);

    if (result == 0) {
        printf("The first 7 characters are equal.\n");
    } else {
        printf("The first 7 characters are not equal.\n");
    }

    return 0;
}

How It Works

Both strings begin with "Hello, " (seven characters). strncmp stops after those seven bytes and returns 0. The rest of each string is never examined.

Example 2 — Prefix Match vs Full String

See how strncmp can report equality when strcmp does not.

C
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *word = "apple";
    const char *longer = "application";

    printf("strncmp(5): %d\n", strncmp(word, longer, 5));
    printf("strcmp:     %d\n", strcmp(word, longer));

    return 0;
}

How It Works

The first five letters of both strings are apple, so strncmp(..., 5) returns 0. strcmp continues past that and finds '\0' in word before the longer string ends, so it returns negative.

📈 Practical Patterns

HTTP methods, mismatches within n, and edge cases.

Example 3 — Check an HTTP Method Prefix

Recognize a request line that starts with GET without parsing the full URL.

C
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *request = "GET /index.html HTTP/1.1";

    if (strncmp(request, "GET ", 4) == 0) {
        printf("GET request detected\n");
    } else if (strncmp(request, "POST", 4) == 0) {
        printf("POST request detected\n");
    } else {
        printf("Other method\n");
    }

    return 0;
}

How It Works

Only the first four bytes matter for this branch. This pattern appears in parsers, config scanners, and protocol handlers where you classify input by a fixed prefix.

Example 4 — Mismatch Within the Limit

When bytes differ before n is reached, the sign tells you which string sorts first.

C
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *a = "cat";
    const char *b = "dog";

    int r = strncmp(a, b, 3);

    if (r < 0) {
        printf("%s comes before %s\n", a, b);
    } else if (r > 0) {
        printf("%s comes after %s\n", a, b);
    } else {
        printf("Equal within 3 chars\n");
    }

    return 0;
}

How It Works

At index 0, 'c' (99) is less than 'd' (100), so the result is negative. Use the sign for ordering, not the exact number.

Example 5 — When n Is Zero

With n = 0, no bytes are compared and the result is always zero.

C
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *x = "completely different";
    const char *y = "nothing alike";

    printf("strncmp with n=0: %d\n", strncmp(x, y, 0));

    return 0;
}

How It Works

This edge case rarely appears in application logic but shows that n controls how much work is done. A zero limit always yields equality without reading either string.

🚀 Common Use Cases

  • Prefix checks — verify filenames, commands, or tags start a certain way.
  • Protocol parsing — classify HTTP methods, MIME types, or magic bytes in headers.
  • Version strings — compare major version digits without the full semver tail.
  • Bounded sorting — order fixed-width keys where only n bytes matter.
  • Safer compares — limit work when strings may be very long.

🧠 How strncmp() Works

1

i = 0

Start at the first byte of s1 and s2.

Init
2

Compare while i < n

Stop on mismatch or if either byte is '\0'.

Loop
3

Return sign

0 if all compared bytes matched; otherwise less or greater.

Result
=

int result

<0, 0, or >0 for the first n bytes.

📝 Notes

  • 0 from strncmp means equal within the limit—not always full-string equality.
  • Comparison is case-sensitive and uses unsigned char values.
  • Not locale-aware; use strcoll for collation rules.
  • Do not pass NULL pointers—behavior is undefined.
  • Large n is safe; the function stops at null terminators anyway.

⚡ Optimization

Passing a small n can avoid scanning very long strings when you only need a prefix. For fixed-size binary blobs without null bytes, consider memcmp(s1, s2, n) instead—it always compares exactly n bytes and does not stop at '\0'.

Conclusion

strncmp() compares at most n bytes of two strings and returns the same style of result as strcmp(). Use it for prefix checks and bounded comparisons; use strcmp() when you need full string equality.

Next, learn strncpy() to copy at most n characters into a buffer.

💡 Best Practices

✅ Do

  • Use strncmp(s1, s2, n) == 0 for prefix equality
  • Pick n as the exact prefix length (include spaces if needed)
  • Follow with strcmp when full match is required
  • Test the sign (<0, >0) for ordering, not exact values
  • Include <string.h>

❌ Don’t

  • Assume strncmp == 0 means strings are identical
  • Use strncmp for case-insensitive user text without normalization
  • Pass NULL for either string
  • Confuse strncmp with memcmp on binary data
  • Expect locale-aware sorting for accented characters

Key Takeaways

Knowledge Unlocked

Five things to remember about strncmp()

Use these points when comparing strings with a length limit.

5
Core concepts
📝 02

0 = prefix

Not full.

Gotcha
🔢 03

Sign only

<0 or >0.

Return
📈 04

vs strcmp

Full scan.

Compare
💬 05

Case matters

Byte compare.

Rules

❓ Frequently Asked Questions

strncmp() compares at most n bytes of two C-strings. It returns 0 if those bytes match, a negative value if s1 is less than s2, or a positive value if s1 is greater than s2—using unsigned char comparison like strcmp().
int strncmp(const char* s1, const char* s2, size_t n); Include <string.h>. Both arguments must point to valid null-terminated strings.
Use strncmp(s1, s2, n) == 0 where n is the prefix length. For example, strncmp("GET /api", "GET ", 4) == 0 checks that s1 starts with "GET ".
strcmp() compares until a difference or both strings end. strncmp(s1, s2, n) compares at most n bytes and stops—even if the full strings differ later. A zero result from strncmp does not mean the entire strings are equal.
strncmp(s1, s2, 0) always returns 0. No characters are compared.
Yes. "Hello" and "hello" differ within the first character. For case-insensitive bounded comparison, use strncasecmp() on POSIX or compare after normalizing case.
Did you know?

The old reference suggested n must stay “within the valid length” of the strings. In standard C, any n is valid—comparison stops at '\0' or after n bytes. The real pitfall is interpreting 0 as full equality: always ask whether you meant prefix match or complete string match.

Continue the String Functions Series

Master bounded comparison with strncmp(), then learn bounded copying 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