I saw few similar solutions, but they all relied on C-style arrays and str utils, so I thought I would write a higher level C++ only implementation with a vector as an exercise. I have not implemented all the functions yet but wanted to first check if this looks to be on the right path or if there are some major issues.
class mystring {
public:
mystring() = default;
explicit mystring(const char* str) {
if (str != nullptr) {
data = std::vector<char>(str, str + strlen(str));
}
}
mystring& operator=(const char* str) {
data.clear();
copy(str, str + strlen(str), back_inserter(data));
}
mystring& operator+=(const mystring& other) {
data.insert(data.end(), other.data.begin(),other.data.end());
return *this;
}
mystring operator+(const mystring& other) const {
mystring result(other);
result += other;
return result;
}
explicit operator const char* () const {
return c_str();
}
const char& operator[](size_t idx) const {
return data[idx];
}
char& operator[](size_t idx) {
return data[idx];
}
void replace(size_t b, size_t e, const char* str) {
data.erase(data.begin()+b, data.begin() + e);
data.insert(data.begin()+b,str,str+strlen(str));
}
friend ostream& operator<<(ostream& cout, const mystring& s);
bool operator==(const mystring& o) const =default;
const char* c_str() const {
return data.data();
}
private:
std::vector<char> data;
};