Advertisement
int ( char * str1, const char * str2, size_t num )
int value | description |
---|---|
0 | when the characters compared between two strings are the same. |
A positive int value | when the non-matching character in the first string is having an ASCII value larger than the character at the same index in second string. |
A negative int value | when the non-matching character in the first string is having an ASCII value smaller
than the character at the same index in second string. |
/* Program to compare n number of characters of first string with another string. */
#include<string.h>
#include<stdio.h>
int main()
{
char first[20] = "North POLE";
char second[20] = "North pole";
char third[10] = "Norway";
printf("The content of first string : %s", first);
printf("\n");
printf("The content of second string : %s", second);
printf("\n");
/* comparing the first 4 characters of first string with the second string */
int result = strncmp(first, second, 4);
printf("Comparing first 4 characters between %s and %s gives : %d", first, second, result);
printf("\n");
/* comparing the first 4 characters of second string with the third string */
result = strncmp(second, third,4); /* strncmp gives the ASCII value difference between the first mismatching characters between the two strings */
printf("Comparing first 4 characters between %s and %s gives : %d", second, third, result);
return 0;
}
The content of first string : North POLE
The content of second string : North pole
Comparing first 4 characters between North POLE and North pole gives : 0
Comparing first 4 characters between North pole and Norway gives : -3
Advertisement
/* strncmp example */
#include<string.h>
#include<stdio.h>
int main()
{
char first[15] = "Never give up!";
char second[15] = "Don't give up";
printf("The content of first string : %s", first);
printf("\n");
printf("The content of second string : %s", second);
printf("\n");
/* comparing the characters of first string with the characters in second string */
int result = strncmp(first, second,4);
printf("Comparing the first 4 characters between %s and %s gives : %d \n", first, second, result);
return 0;
}
The content of first string : Never give up!
The content of second string : Don't give up
Comparing the first 4 characters between Never give up! and Don't give up gives : 10
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement