WAP to overload binary + for concatenate two String & == to compare length of two String
Objective
Write a C++ program to overload the binary (+) and equality (==) operators for custom String manipulation.
Algorithm / Approach
- Create a
class Stringthat holds a character array. - Overload
+:String operator+(String x). Inside, usestrcat()to concatenate the internal arrays. - Overload
==:int operator==(String x). Inside, usestrlen()to compare lengths. - In
main(), usea + bto join two custom String objects anda == bto compare them.
main.cpp
#include<iostream>
#include<string.h>
using namespace std;
class String {
public:
char a[20];
void getString(char x[]) {
strcpy(a,x);
}
void display() {
cout<< a<< endl;
}
String operator+(String x) {
String obj;
strcpy(obj.a,a);
strcat(obj.a,x.a);
return obj;
}
int operator==(String x) {
int len1 = strlen(a);
int len2 = strlen(x.a);
return len1-len2;
}
};
int main() {
String a,b;
char name[30],sec[30];
cout<<"Enter first String ";
cin.getline(name,20);
a.getString(name);
cout<<"Enter Second String ";
cin.getline(sec,30);
b.getString(sec);
a.display();
b.display();
String c;
c = a+b;
c.display();
if((a==b)==0){
cout<<"Same length\n";
}
else {
cout<<"Different length\n";
}
return 0;
}
Expected Output
Enter first String Alok Enter Second String Deepu Alok Deepu AlokDeepu Different length
Explanation of the Program
- Here we are inventing entirely new semantic meanings for standard operators.
- Instead of performing mathematical addition, our overloaded
+operator concatenates strings. Instead of checking for exact value equality, our==operator only checks if the lengths of the two strings are equal.
Complexity
Time Complexity
O(n) - Where n is the string length during strcat and strlen operations.
Space Complexity
O(n) - To store the concatenated string result.