This function compare n character in two strings to find out whether they are same or different.
The two string are compared character by character until there is a mismatch or end of one of the strings is reached, whichever occurs first.
If the two strings are identical, strncmp() return zero.
If they are not, it returns the numeric difference between the ASCII values of the first non-matching pair of characters.
In summarize:
(Compare ASCII values of string's characters)
if both string equal = 0
if first string > second string = +ve
if first string < second string = -ve
Note: strncmp() is case sensitive.
syntax:
strncmp("first_sting","second_string",no_of_character);
example:
strncmp("ABZ","ABC",2);
[Here, There are only first 2 characters are compare.
First string's first character(i.e. A) is ASCII value is 65 and in second string's first character(i.e. B) ASCII value is 66 so first iteration result is 0, now second iteration start, now B and B (i.e. 66 and 66] are comparing so B==B (i.e. 66==66) so result is zero.]
illustrate strncmp() C program:
/*c program for illustrate strncmp() function*/
#include<stdio.h>
int main()
{
int r;
char str1[40],str2[40];
printf("Enter first string : ");
gets(str1);
printf("Enter second string : ");
gets(str2);
r = strncmp(str1,str2,2);
printf("Result : %d",r);
getch();
return 0;
}
The output of above program would be:
Figure: Screen shot for strncmp() function uses in C program |
Related program:
- List of standard library function