C String Functions - C strncmp






Compares strings at most the first n bytes of str1 and str2. Stops comparing after the null character.

Returns zero if the first n bytes (or null terminated length) of str1 and str2 are equal.

Returns less than zero or greater than zero if str1 is less than or greater than str2 respectively.

Prototype

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

Parameter

This function has the following parameter.

str1
C string to be compared.
str2
C string to be compared.
num
Maximum number of characters to compare.

size_t is an unsigned integral type.

Return

Returns an integral value indicating the relationship between the strings:

  • <0 indicates the first character that does not match has a lower value in str1 than in str2
  • 0 indicates the contents of both strings are equal
  • >0 indicates the first character that does not match has a greater value in str1 than in str2




Example


#include <stdio.h>
#include <string.h>
/*  w w  w.j a v a  2  s. co  m*/
int main (){
  char str[][5] = { "R@S#" , "r2s2" , "R2D2" };
  int n;
  for (n=0 ; n<3 ; n++){
    if (strncmp (str[n],"R2xx",2) == 0){
      printf ("found %s\n",str[n]);
    }
  }
  return 0;
}        

The code above generates the following result.





Example 2


#include <string.h>
#include <stdio.h>
 /*from  w  w  w.  j  ava 2  s.c o m*/
void demo(const char* lhs, const char* rhs, int sz)
{
    int rc = strncmp(lhs, rhs, sz);
    if(rc == 0)
        printf("First %d chars of [%s] equal [%s]\n", sz, lhs, rhs);
    else if(rc < 0)
        printf("First %d chars of [%s] precede [%s]\n", sz, lhs, rhs);
    else if(rc > 0)
        printf("First %d chars of [%s] follow [%s]\n", sz, lhs, rhs);
 
}
int main(void)
{
    const char* string = "Hello World!";
    demo(string, "Hello!", 5);
    demo(string, "Hello", 10);
    demo(string, "Hello there", 10);
    demo("Hello, everybody!" + 12, "Hello, somebody!" + 11, 5);
}

The code above generates the following result.