Advertisements
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


Advertisements
Categories: Cpp Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: