标签:ons 长度 bst const data 取子串 字符串类 == pos
1 //字符串类的设计 2 //1.字符串类String能与C语言的字符串兼容使用 3 //2.重载逻辑等于运算符(==) 4 //3.字符串操作包括取字符串长度和取子串 5 #include<string.h> 6 #include<iostream.h> 7 #include<stdlib.h> 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<size;i++){ 44 this->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<length;i++){ 76 *p++=*q++; 77 } 78 79 *p=NULL; 80 temp.size=length+1; 81 82 return temp; 83 } 84 85 String &String::operator =(const String &s){ 86 if(this->size!=s.size){ 87 delete []str; 88 this->str=new char[s.size]; 89 size=s.size; 90 } 91 for(int i=0;i<s.size;i++){ 92 this->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<<str1.Length()<<endl; 127 128 str3=str1.SubStr(5,9); 129 str4=str1.SubStr(5,9); 130 str5="Structure"; 131 132 if(str3==str4){ 133 cout<<"String和String字符串比较"<<endl; 134 } 135 136 if(str5=="Structure"){ 137 cout<<"String和C语言字符串相比较"<<endl; 138 } 139 if("Strcture"==str2){ 140 cout<<"C语言字符串和String相比较"<<endl; 141 } 142 return 0; 143 }
标签:ons 长度 bst const data 取子串 字符串类 == pos
原文地址:https://www.cnblogs.com/Tobi/p/9249788.html