【实验5】c++MyString类实现
ccnu_hupo_cpp_class_tst6exercise2_by:lele_2013_10_30
new不忘delete
Design the string class in the C++ library by providing your own implementation for the following functions (name your class MyString):
MyString();//构造
MyString(const char* cString);//地址不能变
char at(int index) const;//输入数组下标,返回字符
int length() const;//长度
void clear();//清空len=0
bool empty() const;//是否清空?len不变
int compare(const MyString& s) const;//
int compare(int index, int n, const MyString& s) const;
void copy(char s[], int index, int n);
char* data() const;
int find(char ch) const;
int find(char ch, int index) const;
int find(const MyString& s, int index) const;
*/
#include
#include
using namespace std;
class MyString
{
public:
MyString();
MyString(const char* cString);
char at(int index) const;//
int length() const;
void clear();
bool empty() const;
int compare(const MyString& s) const;
int compare(int index, int n, const MyString& s) const;
void copy(char s[], int index, int n);
char* data() const;
int find(char ch) const;
int find(char ch, int index) const;
int find(const MyString& s, int index) const;
~MyString()
cout<<"delete..."< delete []a; } private: char *a; int len; }; MyString::MyString(const char* cString) { if (cString==NULL) { a=new char[1]; a[0]=0; int len=0; } else { a=new char [strlen(cString)+1]; strcpy(a,cString); len=strlen(cString); } } char MyString::at(int index) const { if(len==0) {cout<<"no char in string"< return 0; } if(index>len) { cout<<"the maximun array exceed"< return 0 ; } else { return a[index-1]; } } int MyString::length() const return len; } void MyString::clear() { if(!a) { delete []a; a=NULL; } len=0; //a=" "; } bool MyString::empty() const { if(len==0) return true; else return false; } int MyString::compare(const MyString& s) const { int m=this->len;int n=s.len; for(int i=0;i { if(s.a[i]==a[i]) continue;