#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
class String {
char *str;
unsigned int length;
public:
String() {
str = NULL;
length = 0;
}
String(const char *s){
str = NULL;
length = strlen(s);
if (s) {
str = new char[strlen(s) + 1];
strcpy(str, s);
}
}
String(const String&other) {
str = NULL;
length = strlen(other.str);
if (other.str) {
str = new char[strlen(other.str) + 1];
strcpy(str, other.str);
}
}
~String() {
delete[](str);
length = 0;
}
String& append(const String& other) {
str = strcat(str, other.str);
return *this;
}
String& operator = (const String &other) {
delete[](str);
str = NULL;
length = other.length;
if (other.str) {
str = new char[strlen(other.str) + 1];
strcpy(str, other.str);
}
return *this;
}
String& operator += (const String &other) {
strcat(str, other.str);
length = length + other.length;
return *this;
}
String operator + (const String &other) {
if (str == NULL)
return other;
if (other.str == NULL)
return *this;
String s;
s.length = other.length + length;
s.str = new char[strlen(str) + strlen(other.str) + 1];
strcpy(s.str, str);
strcat(s.str, other.str);
return s;
}
String& operator<< (const String &other) {
if (str == NULL) {
str = new char[strlen(other.str) + 1];
length = other.length;
strcpy(str, other.str);
return *this;
}
if (other.str == NULL)
return *this;
strcat(str, other.str);
length = length + other.length;
return *this;
}
char& operator[](const int n) {
return str[n];
}
friend ostream& operator<< (ostream&out, String& a);
};
ostream& operator<< (ostream&out,String& a) {
printf("%s\n", a.str);
return out;
}
int main() {
String a("This is "), b(a);
String c;
cout << "a:" << a << "\n" << "b:" << b << "\n" << "c:" << c << "\n";
c = "a test.";
cout << "c:" << c << "\n";
a.append(c);
cout << "a:" << a << "\n";
{
String a("Hello"), b;
a += " World";
b << (a + b);
cout << "b:" << b << "\n";
String c;
c = b + "!";
cout << "c:" << c << "\n";
}
a[0] = 't';
cout << "a:" << a << "\n";
return 0;
}