strncmp() is a standard library function in C used to compare the first n characters of two strings. It is similar to strcmp(), but it only compares up to n characters, making it suitable for cases where only part of the strings need to be compared.

strncmp Function Header

The header file for the strncmp function is <string.h>. Before using the strncmp function, make sure to include this header file in your C code:

#include <string.h>

strncmp Function Prototype

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

The strncmp function compares the string pointed to by s1 with the string pointed to by s2, up to n characters; it does not compare the contents after the null character '\0'.

Parameter Explanation

  • s1: Pointer to the first string;

  • s2: Pointer to the second string;

  • n: Maximum number of characters to compare;

Return Value

The strncmp function returns an integer greater than, equal to, or less than 0;

If the two strings are identical, it returns 0, otherwise, it returns the difference between the first differing characters.

strncmp Example Code

strncmp() is commonly used to compare if the first n characters are the same:

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

int main() {

    char str1[] = "perfcode.com";
    char str2[] = "perFCODE.com";
    
    // Compare the first 3 characters
    if (strncmp(str1, str2, 3) == 0) {
        printf("The first 3 characters are the same.\n");
    } else {
        printf("The first 3 characters are different.\n");
    }
    
    // Compare the first 5 characters
    if (strncmp(str1, str2, 5) == 0) {
        printf("The first 5 characters are the same.\n");
    } else {
        printf("The first 5 characters are different.\n");
    }

    return 0;
}

Program Output

The first 3 characters are the same.
The first 5 characters are different.