strncmp C Library Function

The function int strncmp(const char *str1, const char *str2, size_t n); compares first n characters string pointed by str1 with first n characters of string pointed by str2. This function compares both string character by character. It will compare till n characters until the characters mismatch or a terminating null-character is reached.

Function prototype of strncmp

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

  • str1 : A pointer to a C string to be compared.
  • str2 : A pointer to a C string to be compared.
  • n : Maximum number of characters to compare.

Return value of strncmp

Return Value Description
Positive (>0) str2 is less than str1
Zero (==0) str1 is equal to str2
Negative (<0) str1 is less than str2

C program using strncmp function

The following program shows the use of strncmp function to compare first n characters of two strings.

strncmp C Library Function

#include <stdio.h>
#include <string.h>
#include <conio.h>
 
int main()
{
   char firstString[100], secondString[100];
   int response, n;
   printf("Enter first string\n");
   scanf("%s", &firstString);
   printf("Enter second string\n");
   scanf("%s", &secondString);
   printf("Enter number of characters to compare\n");
   scanf("%d", &n);
    
   response = strncmp(firstString, secondString, n);
 
   if(response > 0){
      printf("second String is less than first String");
   } 
   else if(response < 0) {
      printf("first String is less than second String");
   }
   else {
      printf("first String is equal to second String");
   }
    
   getch();
   return(0);
}

Output

Enter first string
ASDFGiuyiu
Enter second string
ASDFGiuhkjshfk
Enter number of characters to compare
5
first String is equal to second String