Friday, December 11, 2009

String Compare Without Strcmp( ) function:

Today I’m going to give you a program to compare two string without strcmp( ) function. First of all, we’ll first understand what’s the operation of strcmp function.
This is the general format of strcmp function. It contains two strings and it compares two strings returns a number.

Consider two strings “ab”, “aB”
n=strcmp(“ab”, “aB”);
Ok now listen carefully.

Strcmp function operation:
At first ,it’ll compare 1st character of strings ‘a’ and ‘a’(how it compare means just find the difference of ascii values of them i.e., 97-97=0) if difference is zero , it’ll continue to compare next character.
Then , it’ll compare 2nd character of strings ‘b’ and ‘B’(but here notice that ascii value of ‘b’ is 98 but incase of ‘B’ is 66 so difference is 98-66=32) difference is 32. it’ll return 32 .

Note: ‘a’ ascii value is 97, ‘b’=98, ’c’=99,….
‘A’ ascii value is 65, ‘B’=66, ‘C’= 67,…..
‘0’ ascii value is 48 ,’1’=49,…..

Consider two strings “aB”,”aCd”

What’ll do strcmp function for these strings?
As mentioned above , it’ll compare 1st character of strings ‘a’ and ‘a’. here difference is 0
Then, it’ll compare 2nd character of strings ‘B’ and ‘C’(difference= 66-67) so now value is -1 not equal to zero so it’ll return value as -1


#include< iostream.h >
#include< conio.h >
int shark(char a[],char b[]);
void main( )
char a[10],b[10];
int c;
clrscr( );
cin > > a > > b;
cout < < c;
int shark(char a[],char b[])
int t=0;
for( int i=0;a[i]!=’\0’;i++); //Finding length of 1st string
for(int j=0;b[j]!=’\0’j++); //Finding length of 2nd string
for(int k=0,l=0;(k < i)&&(l < j);k++,l++)
if(k!=i&&t = =0)
for(int m=k;m < i;m++)
else if(l!=j&&t = =0)
for(int m=l;m < j;m++)
return t;


Post a Comment