C programming strncmp string.h

In C programming the <string.h> strncmp function compares two strings for specific number of characters.The declaration of the function is given below.

int strncmp(const char *s1, const char *s2, size_t n);

s1 -The first string.

s2 -The second string.

n -The number of characters to compare in ‘s1’ and ‘s2’.

Return type
int -Returns 0 if ‘n’ number of characters are equal in ‘s1’ and ‘s2’.Returns value greater than 0(most probably 1) if s1 is greater than s2.Returns value lesser than 0(most probably -1) if s1 is lesser than s2.

If null-terminating character occur before ‘nth’ number of characters the characters after the null character is neglected.

Code example

char s1[] = “New string”, s2[] = “New String”;

int ret ;

ret = strncmp(s1 , s2 , 4);

printf(“ret=%d”, ret);

ret = strncmp(s1 , s2 , strlen(s1) );

printf(“\nret=%d”, ret);



The fifth character of s1 i.e. ‘s’,is greater than the 5th character of s2 i.e. ‘S’ so the second output is 1.

Related links

->C strcmp string.h

->C memcmp string.h

->C strcoll string.h