[Typical interview questions] [Baidu] c ++ implements the string class in STL
Question
Use c ++ to implement the string class in stl, including construction, copy construction, destructor, assignment, comparison, string addition, length and substring acquisition.
Code
/* ----------------------------------- * Date: 2015-03-31 * Author: SJF0115 * Subject: Implementation of string class * Source: Baidu * blog: ---------------------------------- */# include
# Include
Using namespace std; class String {public: // default constructor String (const char * str = NULL); // copy const String (const String & str ); // destructor ~ String (); // String connection String operator + (const String & str); // String value assignment String & operator = (const String & str ); // String value: String & operator = (const char * str); // determines whether the String is equal bool operator = (const String & str ); // obtain the String length int length (); // obtain the substring [start, start + n-1] String substr (int start, int n ); // reload the output of friend ostream & operator <(ostream & o, const String & str); private: char * data; int size ;}; // constructor String: Stri Ng (const char * str) {if (str = NULL) {data = new char [1]; data [0] = '\ 0'; size = 0 ;} // if else {size = strlen (str); data = new char [size + 1]; strcpy (data, str );} // else} // copy constructor String: String (const String & str) {size = str. size; data = new char [size + 1]; strcpy (data, str. data);} // destructor String ::~ String () {delete [] data;} // String connection String: operator + (const String & str) {String newStr; // release the original space delete [] newStr. data; newStr. size = size + str. size; newStr. data = new char [newStr. size + 1]; strcpy (newStr. data, data); strcpy (newStr. data + size, str. data); return newStr;} // String value: String & String: operator = (const String & str) {if (data = str. data) {return * this;} // if delete [] data; size = str. size; data = new char [size + 1]; strcpy (data, str. data); return * this;} // String value String & String: operator = (const char * str) {if (data = str) {return * this ;} // if delete [] data; size = strlen (str); data = new char [size + 1]; strcpy (data, str); return * this ;} // determine whether the String is equal to bool String: operator = (const String & str) {return strcmp (data, str. data) = 0;} // obtain the String length int String: length () {return size;} // obtain the substring [start, start + n-1] String :: substr (int start, int n) {String newStr; // release the original memory delete [] newStr. data; // re-apply for memory newStr. data = new char [n + 1]; for (int I = 0; I <n; ++ I) {newStr. data [I] = data [start + I];} // for newStr. data [n] = '\ 0'; newStr. size = n; return newStr ;}// reload the output ostream & operator <(ostream & o, const String & str) {o <
"<