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.
int strncmp(const char *str1 , const char *str2 , size_t n );
This function has the following parameter.
size_t is an unsigned integral type.
Returns an integral value indicating the relationship between the strings:
#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.
#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.