- Get link
- X
- Other Apps
Featured Post
Posted by
Unknown
on
- Get link
- X
- Other Apps
Here's a simple implementation of strcmp function of string library.
It returns -1 if the first string is less than second , 1 if second string is less than first and 0 if the strings are equal.
It returns -1 if the first string is less than second , 1 if second string is less than first and 0 if the strings are equal.
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *string1,*string2; //variables to store inputs to be compared
int ret; //variable to collect return value
char *temp1,*temp2;
/*function prototype it takes strings to be compared and returns value accordingly*/
int my_strcmp(const char *temp1,const char *temp2);
string1=(char*)malloc(20);
string2=(char*)malloc(20);
temp1=string1;
temp2=string2;
printf("enter two strings to be compared :\n");
temp1=string1;
temp2=string2;
fgets(string1,20,stdin); //taking input from user
fflush(stdin);
fgets(string2,20,stdin); //taking input from user
while(*temp1)
{
temp1++;
}
temp1--;
if(*temp1=='\n')
{
*temp1='\0';
}
while(*temp2)
{
temp2++;
}
temp2--;
if(*temp2=='\n')
{
*temp2='\0';
}
ret=my_strcmp(string1,string2);
printf("\nthe return value is %d\n",ret);
free(string1);
free(string2);
return EXIT_SUCCESS;
}
int my_strcmp(const char *temp1,const char *temp2)
{
while(*temp1 && *temp2)
{
if(*temp1==*temp2)
{
temp1++;
temp2++;
}
else
{
if(*temp1<*temp2)
{
return -1; //returning a negative value
}
else
{
return 1; //returning a positive value
}
}
}
return 0; //return 0 when strings are same
}
Comments
Post a Comment
Please post your valuable suggestions