Latest web development tutorials

C library functions - strncmp ()

C standard library - <string.h> C standard library - <string.h>

description

C library functionsint strncmp (const char * str1, const char * str2, size_t n) is compared to str1andstr2,compare up to beforenbytes.

statement

Here is strncmp () function's declaration.

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

parameter

  • str1 - The first string to be compared.
  • str2 - to compare the second string.
  • n - maximum number of characters to compare.

return value

This function returns the following values:

  • If the return value <0, the str1 is less than str2.
  • If the return value> 0 indicates less than str2 str1.
  • If the return value = 0, then str1 is equal to str2.

Examples

The following example demonstrates the use of 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 小于 str2");
   }
   else if(ret > 0) 
   {
      printf("str2 小于 str1");
   }
   else 
   {
      printf("str1 等于 str2");
   }
   
   return(0);
}

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

str2 小于 str1

C standard library - <string.h> C standard library - <string.h>