Copyright © tutorialspoint.com

C - strncmp function

previous

Synopsis:

#include <stdio.h>

int strncmp(char *string1, char *string2, int n); 

Description:

The strncmp function compares first n characters of string1 and string2 and returns a value indicating their relationship.

Return Value

  • if Return value if < 0 then it indicates string1 is less than string2

  • if Return value if > 0 then it indicates string2 is less than string1

  • if Return value if = 0 then it indicates string1 is equal to string1

Example

#include <stdio.h>

int main() {
  char string1[20];
  char string2[20];

  strcpy(string1, "Hello");
  strcpy(string2, "Hellooo");
  printf("Return Value is : %d\n", strncmp( string1, string2, 4));

  strcpy(string1, "Helloooo");
  strcpy(string2, "Hellooo");
  printf("Return Value is : %d\n", strncmp( string1, string2, 10));

  strcpy(string1, "Hellooo");
  strcpy(string2, "Hellooo");
  printf("Return Value is : %d\n", strncmp( string1, string2, 20));

  return 0;
}

It will proiduce following result:

Return Value is : 0
Return Value is : 111
Return Value is : 0

previous

Copyright © tutorialspoint.com