In C Language, we use strcmp() or strcmpi() functions to compare two strings. In C++ programs also we use these functions to perform the same job. Operator overloading in C++ helps us to use equality operator to compare two strings in C++ programs.
Here is a C++ program to compare two strings using operator overloading.
#include< iostream.h >
#include< conio.h >
#include< string.h >
const int SIZE=40;
class String
{
private:
char str [SIZE];
public:
String ()
{
strcpy (str," ");
}
String (char ch [])
{
strcpy (str, ch);
}
void getString ()
{
cout<< "Enter the string: -";
cin.get (str, SIZE);
}
int operator == (String s)
{
if (strcmp (str, s.str)==0)
return 1;
else
return 0;
}
};
void main ()
{
clrscr ();
String s1, s2, s3;
s1="Satavisha";
s2="Suddhashil";
s3.getString ();
if (s3==s1)
cout<< "1st and 3rd string are same.";
else if (s2==s3)
cout<< "2nd and 3rd string are same.";
else
cout<< "All strings are unique.";
getch ();
}
Operator overloading is an important chapter in and Students can ask any related question through this blog.
No comments:
Post a Comment