#include <cstring> class String { friend ostream &operator<< (ostream &os, const String &s); public: String() {copy();} String(const char *init) {copy(init);} String(const String &rhs) {copy(rhs.m_data);} String& operator= (const String &rhs); ~String() {delete[] m_data;} int find(const String &sub) const; //should use KMP algorithm size_t length() const {return strlen(m_data);} private: char *m_data; void copy(const char *src = NULL); }; ostream &operator<< (ostream &os, const String &s) { os<<s.m_data; return os; } void String::copy(const char *src) { if(src == NULL){ m_data = new char[1]; m_data[0] = '/0'; }else{ size_t size = strlen(src) + 1; m_data = new char[size]; strncpy(m_data, src, size); } } String& String::operator= (const String &rhs) { if(this != &rhs){ this->~String(); copy(rhs.m_data); } return *this; } int String::find(const String &sub) const { if(sub.length() <= length()){ bool include = false; for(int i = 0; i <= static_cast<int>(length()-sub.length()); ++i){ include = true; for(int j = i, k = 0; k < static_cast<int>(sub.length()); ){ if(m_data[j++] != sub.m_data[k++]){ include = false; break; } } if(include){ return i; } } } return -1; }