Thursday, July 9, 2009

How to Compare Two Strings in C Programming?

strcmp( const char *cmp1, const char *cmp2 );





it will return zero if they are equal, non-zero (see detail in source link) means not equal.

How to Compare Two Strings in C Programming?
using string function strcmp i.e


int strcmp(const char *str1,const char *str2)


wat i have studied is this rest i dont no.
Reply:You can use the function strcmp. The function interface is int


strcmp(const char *s1, const char *s2), where s1 and s2 are the functions which needs to be compared. The function returned zero if the two strings are equal. A non zero value means the strings are not equal. But this value itself has some meaning. Its a big explanation and cant be given here.
Reply:#include %26lt;stdio.h%26gt;


#include%26lt;conio.h%26gt;


#include%26lt;string.h%26gt;


main()


{


string str1;


string str2;


gets(str1);// accept first string


gets(str2);// accept second string


// compare both strings


if(strcmp(str1,str2) %26gt; 0)


printf(str1 + " is greater than " + str2);


elseif(strcmp(str1,str2) %26lt; 0)


printf(str2 + " is greater than " + str1);


else


printf(str1 + " is equal to " + str2);


getch();


return 0;


}
Reply:To compare two strings, you need to use comparestring function.
Reply:strcmp() is the best function i think but it has been declared depracated in Visual Studio .NET 2005.





The following safe function can be used instead. The parameter


max ensures that the function will safely return even if parameter strings are not null terminated.





int compare(char* a, char* b, int max)


{


int i=0;





while(a[i]%26amp;%26amp;max)


{


if(a[i]!=b[i]) return 0;


max--;


i++;


}





return 1;


}


No comments:

Post a Comment