Sunday, July 12, 2009

How to compare two strings in c++?

please give me an program

How to compare two strings in c++?
As below using strcmp








/* strcmp example */


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


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





int main ()


{


char szKey[] = "apple";


char szInput[80];


do {


printf ("Guess my favourite fruit? ");


gets (szInput);


} while (strcmp (szKey,szInput) != 0);


puts ("Correct answer!");


return 0;


}
Reply:http://www.cplusplus.com/reference/strin...
Reply:strcmp
Reply:simplest example of all..





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


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





int main()


{


char one[10],two[10];


cout%26lt;%26lt;"\nEnter first string:";


cin%26gt;%26gt;one;


cout%26lt;%26lt;"\nEnter second string:";


cin%26gt;%26gt;two;





if(strcmp(one,two))


cout%26lt;%26lt;"\nThey r not equal";


else


cout%26lt;%26lt;"\nStrings are equal";


return 0;


}
Reply:Strings can be compared by using library function strcmp, for this header file "string.h" must be included. Function receive two string argument and returns 0 when string1 is same as string2, returns +ve no when string1 is greater than string2 and returns -ve no when string1 is less than string2.





Syntex:- int strcmp(char*,char*)


e.g.


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


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


void main()


{


char *st1="Ajay Kumar", *st2="Amit Kumar";





cout%26lt;%26lt;strcmp(st1,st2);


}





function will display -3 because second string is greater (according to alphabet) i.e. j - m = -3
Reply:if possible use strcmp of string.h





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


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





void main()


{


char str[2][40],i=0;





clrscr();


cout%26lt;%26lt;"\n Enter two strings to compare,\n\n 1. ";


cin%26gt;%26gt;str[0];


cout%26lt;%26lt;" 2. ";


cin%26gt;%26gt;str[1];





while(str[0][i]!='\0' || str[1][i]!='\0')


{


if(str[0][i]!=str[1][i])


{


i=-1;


break;


}


i++;


}





cout%26lt;%26lt;"\n\n The given strings ";


if(i==-1)


cout%26lt;%26lt;str[0]%26lt;%26lt;" and "%26lt;%26lt;str[1]%26lt;%26lt;" are different.";


else


cout%26lt;%26lt;str[0]%26lt;%26lt;" and "%26lt;%26lt;str[1]%26lt;%26lt;" are same.";


getch();


}
Reply:For the best possible answers always check http://www.codeproject.com/


No comments:

Post a Comment