What is strncmp() Function in C language?

The C library function strncmp() compares at most the first n characters of two strings lexicographically. It returns an integer value indicating the relationship between the strings based on the first n characters.

Syntax

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

Parameters

  • str1 − First string to be compared
  • str2 − Second string to be compared
  • n − Maximum number of characters to compare

Return Value

  • 0 − If the first n characters of both strings are equal
  • Positive value − If str1 is lexicographically greater than str2
  • Negative value − If str1 is lexicographically less than str2

Example 1: Basic String Comparison

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

int main() {
    char str1[] = "Hello";
    char str2[] = "Help";
    int result;
    
    result = strncmp(str1, str2, 3);
    printf("Comparing first 3 characters:<br>");
    printf("strncmp("%s", "%s", 3) = %d<br>", str1, str2, result);
    
    result = strncmp(str1, str2, 4);
    printf("Comparing first 4 characters:<br>");
    printf("strncmp("%s", "%s", 4) = %d<br>", str1, str2, result);
    
    return 0;
}
Comparing first 3 characters:
strncmp("Hello", "Help", 3) = 0
Comparing first 4 characters:
strncmp("Hello", "Help", 4) = 8

Example 2: Practical Usage

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

int main() {
    char password[] = "secret123";
    char input[] = "secret456";
    
    // Compare only first 6 characters
    if (strncmp(password, input, 6) == 0) {
        printf("Password prefix matches!<br>");
    } else {
        printf("Password prefix doesn't match!<br>");
    }
    
    // Compare entire strings for reference
    if (strcmp(password, input) == 0) {
        printf("Complete password matches!<br>");
    } else {
        printf("Complete password doesn't match!<br>");
    }
    
    return 0;
}
Password prefix matches!
Complete password doesn't match!

Key Points

  • The strncmp() function stops comparing after n characters or when a null terminator is encountered.
  • It performs case-sensitive comparison using ASCII values.
  • Unlike strcmp(), it provides controlled comparison for a specific number of characters.
  • The function is declared in <string.h> header file.

Conclusion

The strncmp() function is essential for comparing specific portions of strings in C. It provides safe string comparison by limiting the number of characters compared, preventing buffer overruns and enabling prefix-based string matching.

Updated on: 2026-03-15T13:24:22+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements