Home
> Cpp > C++ Program to implement Operator Overloading for String Comparison with relational op (+, , ==) – Q18
C++ Program to implement Operator Overloading for String Comparison with relational op (+, , ==) – Q18
Q18. Program to implement Operator Overloading for String Comparison with relational op (+, , ==):
Implement the operator overloading for following relational operators for two different strings
– Concatenate two strings using +
– Compare two strings with following overloaded operator >, <, ==
… from College notes (BCA/MCA assignments):
#include <iostream.h> #include <conio.h> #include <string.h> class CStrings{ private: char str[20]; public: void getdata(); friend CStrings operator+(CStrings&, CStrings&); friend int operator<(CStrings&, CStrings&); friend int operator>(CStrings&, CStrings&); friend int operator==(CStrings&, CStrings&); }; void CStrings :: getdata(){ cout<<"\n Enter a String: "; cin>>str; } CStrings operator+(CStrings &s1, CStrings &s2){ CStrings Os; strcpy(Os.str, s1.str); strcat(Os.str, s2.str); cout<<"\n Concatenation of Str1 & str2: "<<Os.str; return Os; } int operator<(CStrings &s1, CStrings &s2){ if(strcmp(s1.str, s2.str) < 0) return 1; else return 0; } int operator>(CStrings &s1, CStrings &s2){ if(strcmp(s1.str, s2.str) > 0) return 1; else return 0; } int operator==(CStrings &s1, CStrings &s2){ if(strcmp(s1.str, s2.str) == 0) return 1; else return 0; } void main(){ clrscr(); CStrings Ostr, Ostr1, Ostr2; cout<<"\n Enter the Information:-"<<endl; Ostr1.getdata(); Ostr2.getdata(); cout<<"\n String Concatenation:-"<<endl; Ostr = Ostr1 + Ostr2; cout<<"\n String Comparison:-"<<endl; if(Ostr1 < Ostr2) cout<<endl<<"\t str1 is less than str2"; else if(Ostr1 > Ostr2) cout<<endl<<"\t str1 is greater than str2"; else if(Ostr1 == Ostr2) cout<<endl<<"\t str1 and str2 are equal."; getch(); }
Output:
Enter the Information:-
Enter a String: manoj
Enter a String: pandey
String Concatenation:-
Concatenation of Str1 & str2: manojpandey
String Comparison:-
str1 is less than str2
Categories: Cpp
Cpp, Operator Overloading
Comments (0)
Trackbacks (0)
Leave a comment
Trackback