0% found this document useful (0 votes)
21 views1 page

String Concatenation

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views1 page

String Concatenation

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#include <iostream>

#include <cstring>

using namespace std;

class String {
private:
char* str;
public:
String() {
str = NULL;
}
String(const char* s) {
str = new char[strlen(s) + 1];
strcpy(str, s);
}
~String() {
if(str) delete [] str;
}
void display() {
cout << str << endl;
}
void set(const char* s) {
if(str) delete [] str;
str = new char[strlen(s) + 1];
strcpy(str, s);
}
String operator+(const String& s) {
String temp;
temp.str = new char[strlen(str) + strlen(s.str) + 1];
strcpy(temp.str, str);
strcat(temp.str, s.str);
return temp;
}
bool operator==(const String& s) {
return (strcmp(str, s.str) == 0);
}
};

int main() {
String s1("Hello"), s2("World"), s3;
s1.display();
s2.display();
s3 = s1 + s2;
s3.display();
if(s1 == s2) {
cout << "s1 and s2 are equal" << endl;
}
else {
cout << "s1 and s2 are not equal" << endl;
}
if(s1 == String("Hello")) {
cout << "s1 and \"Hello\" are equal" << endl;
}
else {
cout << "s1 and \"Hello\" are not equal" << endl;
}
return 0;
}

You might also like