1 //字符串类的设计 2 //1.字符串类String能与C语言的字符串兼容使用 3 //2.重载逻辑等于运算符(==) 4 //3.字符串操作包括取字符串长度和取子串 5 #include6 #include 7 #include 8 class String{ 9 private: 10 char *str; 11 int size; 12 public: 13 // String(); 14 String(char *s=""); 15 String(const String &s); 16 ~String(); 17 18 int Length()const; 19 String SubStr(int pos,int length); 20 21 String &operator=(const String &s); 22 String &operator=(char *s); 23 24 int operator==(const String &s)const; 25 int operator==(char *s)const; 26 27 friend int operator==(char *strL,const String &strR); 28 }; 29 30 //String::String(){} 31 String::String(char *s){ 32 this->size=strlen(s)+1; 33 str=new char[size]; 34 strcpy(str,s); 35 } 36 37 String::String(const String &s){ 38 this->size=s.size; 39 str=new char[size]; 40 if(str==NULL){ 41 exit(0); 42 } 43 for(int i=0;i str[i]=s.str[i]; 45 } 46 } 47 48 String::~String(){ 49 delete []this->str; 50 } 51 52 53 int String::Length()const{ 54 return this->size; 55 } 56 57 String String::SubStr(int pos,int length){ 58 int charsLeft=size-pos-1; 59 String temp; 60 char *p,*q; 61 62 if(pos>=size-1){ 63 return temp; 64 } 65 if(length>charsLeft){ //长度不能超出范围 66 length=charsLeft; 67 } 68 delete []temp.str; 69 70 temp.str=new char[length+1]; 71 72 p=temp.str; 73 q=&this->str[pos]; 74 75 for(int i=0;i size!=s.size){ 87 delete []str; 88 this->str=new char[s.size]; 89 size=s.size; 90 } 91 for(int i=0;i str[i]=s.str[i]; 93 } 94 return *this; 95 96 } 97 98 String &String::operator=(char *s){ 99 int length=strlen(s);100 if(this->size!=length){101 delete []this->str;102 str=new char[length+1];103 this->size=length+1;104 }105 strcpy(this->str,s);106 return *this;107 }108 109 int String::operator==(const String &s)const{ //String类和String类相比较110 return strcmp(this->str,s.str)==0;111 }112 int String::operator==(char *s)const{ //String类和C语言字符串比较113 return strcmp(this->str,s)==0;114 }115 116 int operator==(char *strL,const String &strR){ //C预压字符串和String类比较117 return strcmp(strL,strR.str)==0;118 }119 120 int main(){121 122 String str1("Data Structure");123 String str2("Structure");124 String str3,str4,str5;125 126 cout< <