Easy Tutorial
❮ C Examples Lexicographical Order C Function Abs ❯

C Library Function - strncmp()

C Standard Library - <string.h>

Description

The C library function int strncmp(const char *str1, const char *str2, size_t n) compares up to n bytes of str1 and str2.

Declaration

Here is the declaration for the strncmp() function.

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

Parameters

Return Value

The function returns the following values:

Example

The following example demonstrates the use of the strncmp() function.

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

int main ()
{
   char str1[15];
   char str2[15];
   int ret;

   strcpy(str1, "abcdef");
   strcpy(str2, "ABCDEF");

   ret = strncmp(str1, str2, 4);

   if(ret < 0)
   {
      printf("str1 is less than str2");
   }
   else if(ret > 0) 
   {
      printf("str2 is less than str1");
   }
   else 
   {
      printf("str1 is equal to str2");
   }

   return(0);
}

Let's compile and run the above program, which will produce the following result:

str2 is less than str1

C Standard Library - <string.h>

❮ C Examples Lexicographical Order C Function Abs ❯