1 //design of String class2 //1. String literals can be used in a string compatible with the C language3 //2. Overloaded logic equals operator (= =)4 //3. String manipulation involves taking string lengths and fetching substrings5#include <string.h>6#include <iostream.h>7#include <stdlib.h>8 classstring{9 Private:Ten Char*str; One intsize; A Public: - //String (); -String (Char*s=""); theString (ConstString &s); -~String (); - - intLength ()Const; +String SubStr (intPosintlength); - +String &operator=(ConstString &s); AString &operator=(Char*s); at - int operator==(ConstString &s)Const; - int operator==(Char*s)Const; - -Friendint operator==(Char*strl,ConstString &STRR); - }; in - //string::string () {} toString::string (Char*s) { + This->size=strlen (s) +1; -Str=New Char[size]; the strcpy (str,s); * } $ Panax NotoginsengString::string (ConstString &s) { - This->size=s.size; theStr=New Char[size]; + if(str==NULL) { AExit0); the } + for(intI=0; i<size;i++){ - This->str[i]=S.str[i]; $ } $ } - -string::~String () { the Delete[] This-str; - }Wuyi the - intString::length ()Const{ Wu return This-size; - } About $String String::substr (intPosintlength) { - intcharsleft=size-pos-1; - String temp; - Char*p,*Q; A + if(pos>=size-1){ the returntemp; - } $ if(Length>charsleft) {//length cannot go beyond range theLength=Charsleft; the } the Delete[]temp.str; the -Temp.str=New Char[length+1]; in thep=Temp.str; theq=& This-Str[pos]; About the for(intI=0; i<length;i++){ the*p++=*q++; the } + -*p=NULL; thetemp.size=length+1;Bayi the returntemp; the } - -String &string::operator=(ConstString &s) { the if( This->size!=s.size) { the Delete[]str; the This->str=New Char[s.size]; theSize=s.size; - } the for(intI=0; i<s.size;i++){ the This->str[i]=S.str[i]; the }94 return* This; the the } the 98String &string::operator=(Char*s) { About intLength=strlen (s); - if( This->size!=length) {101 Delete[] This-str;102Str=New Char[length+1];103 This->size=length+1;104 } thestrcpy This-str,s);106 return* This;107 }108 109 intString::operator==(ConstString &s)Const{//String class and String class compared the returnstrcmp This->STR,S.STR) = =0;111 } the intString::operator==(Char*s)Const{//String class and C language string comparison113 returnstrcmp This->str,s) = =0; the } the the int operator==(Char*strl,ConstString &STRR) {//c preload string and string class comparison117 returnstrcmp (strl,strr.str) = =0;118 }119 - intMain () {121 122String str1 ("Data Structure");123String str2 ("Structure");124 String STR3,STR4,STR5; the 126Cout<<str1. Length () <<Endl;127 -Str3=str1. SUBSTR (5,9);129Str4=str1. SUBSTR (5,9); thestr5="Structure";131 the if(str3==STR4) {133cout<<"String and string string comparisons"<<Endl;134 }135 136 if(str5=="Structure"){137cout<<"String and C strings compared"<<Endl;138 }139 if("strcture"==str2) { $cout<<"C-language strings and string comparisons"<<Endl;141 }142 return 0;143}
C + + learning (13)