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<iostream>
#include<cstring>
using namespace std;
int main()
{
char first[20] = "North POLE";
char second[20] = "North pole";
char third[10] = "Norway";
cout<<"The content of first string : " <<first <<"\n";
cout<<"The content of second string : " << second <<"\n";
// comparing the first 4 characters of first string with the second string
int result = strncmp(first, second, 4);
cout<<"Comparing first 4 characters between " <<first <<" and " <<second <<" : " <<result <<"\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 */
cout<<"Comparing first 4 characters between " <<second <<" and " <<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<iostream>
#include<cstring>
using namespace std;
int main()
{
char first[15] = "Never give up!";
char second[15] = "Don't give up";
cout<< "The content of first string : " << first << "\n";
cout<< "The content of second string : " << second << "\n";
// comparing the characters of first string with the characters in second string
int result = strncmp(first, second,4);
cout<< "Comparing the first 4 characters between " << first << " and " << 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