Strncmp is a predefined library function present in string.h file, it used to compare two strings and display which string is greater.
The strcmp fucntion (String comparison)
This function compares 2 strings. It returns the ASCII difference of the first two non– matching characters in both the strings.
Syntax
int strcmp (string1, string2);
If the difference is equal to zero, then string1 = string2.
If the difference is positive, then string1> string2.
If the difference is negative, then string1 <string2.
Example
The strncmp function
This function is used for comparing first ‘n’ characters of 2 strings.
Syntax
strncmp ( string1, string2,2)
Program
#include<stdio.h> #include<string.h> void main(){ //Declaring two strings// char string1[25],string2[25]; int value; //Reading string 1 and String 2// printf("Enter String 1: "); gets(string1); printf("Enter String 2: "); gets(string2); //Comparing using library function// value = strncmp(string1,string2,4); //If conditions// if(value==0){ printf("%s is same as %s",string1,string2); } else if(value>0) { printf("%s is greater than %s",string1,string2); } else { printf("%s is less than %s",string1,string2); } }
Output
Enter String 1: Tutorials Enter String 2: Point Tutorials is greater than Point