Skip to content

Instantly share code, notes, and snippets.

@boki1
Last active June 21, 2019 12:03
Show Gist options
  • Save boki1/16c86049c5b48678d32a0d2a02e9dfe9 to your computer and use it in GitHub Desktop.
Save boki1/16c86049c5b48678d32a0d2a02e9dfe9 to your computer and use it in GitHub Desktop.
Implement string class
#include <iostream>
#include <cstring>
#include "str.h"
namespace str {
str::str() : buffer(0) {}
str::~str() { delete[] this->buffer; }
str::str(const char *src) {
buffer = new char[strlen(src) + sizeof ""];
strcpy(buffer, src);
}
str::str(const str &src) {
buffer = new char[strlen(src.buffer) + sizeof ""];
strcpy(buffer, src.buffer);
}
str &str::operator=(const char *p) {
delete[] this->buffer;
this->buffer = new char[strlen(p) + sizeof ""];
strcpy(this->buffer, p);
return *this;
}
str &str::operator=(const str &p) {
delete[] this->buffer;
this->buffer = new char[strlen(p.buffer) + sizeof ""];
strcpy(this->buffer, p.buffer);
return *this;
}
str str::operator+(const char *other) const {
str res;
res.buffer = new char[strlen(this->buffer) + strlen(other) + sizeof ""];
strcpy(res.buffer, this->buffer);
strcat(res.buffer, other);
return res;
}
str str::operator+(const str &other) const {
str res;
res.buffer = new char[strlen(this->buffer) + strlen(other.buffer) + sizeof ""];
strcpy(res.buffer, this->buffer);
strcat(res.buffer, other.buffer);
return res;
}
char str::operator[](int idx) const {
return this->buffer[idx];
}
str::operator const char *() const {
return this->buffer;
}
int str::size() const {
int i = 0;
while (this->buffer[i]) ++i;
return i;
}
extern "C" void init() {
str x = "DOCTOR";
str y = " WHO";
str z = "?";
str t = x + y + z;
printf("Full str: %s\nIndexed: ", (const char *) t);
for (int i = 0; i < t.size(); ++i)
printf("%c ", t[i]);
}
}
int main() {
str::init();
return 0;
}
#ifndef STR_H
#define STR_H
namespace str {
struct str {
public:
str();
str(const char *);
str(const str &);
~str();
str operator+(const str &) const;
str operator+(const char *) const;
str &operator=(const str &);
str &operator=(const char *);
char operator[](int idx) const;
operator const char *() const;
int size() const;
private:
char *buffer;
};
}
#endif // STR_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment