📄 string.cpp
字号:
// String.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream.h"
#include "String00.h"
#include "string.h"
#include "stdlib.h"
# define maxlen 128
String00::String00(const String00 & ob)
{ch=new char[maxlen+1];
if(!ch) { cerr<<"Allocation Error\n"; exit(1);}
curlen=ob.curlen;
strcpy(ch,ob.ch);
}
String00:: String00(const char *init){
ch=new char[maxlen+1];
if(!ch) { cerr<<"Allocation Error\n"; exit(1);}
curlen=strlen(init);
strcpy(ch,init);
}
String00:: String00(){
ch=new char[maxlen+1];
if(!ch) { cerr<<"Allocation Error\n"; exit(1);}
curlen=0;
ch[0]='\0';
}
String00 &String00:: operator()(int pos,int len){
String00 * temp=new String00();
if(pos<0||pos+len-1>=maxlen||len<0){
temp->curlen=0; temp->ch[0]='\0';
}
else {
if(pos+len-1>=curlen)len=curlen-pos;
temp->curlen=len;
for(int i=0,j=pos;i<len;i++,j++)
temp->ch[i]=ch[j];
temp->ch[len]='\0';
}
return *temp;
}
String00 &String00::operator=(const String00 &ob)
{
if(&ob!=this){
delete[]ch;
ch=new char[maxlen+1];
if(!ch){cerr<<"out of memory!\n"; exit(1);}
curlen=ob.curlen;
strcpy(ch,ob.ch);
}
else cout<<"Attempted assignment of a String to itself! \n";
return *this;
}
String00 &String00:: operator +=(const String00 & ob)
{
char * temp=ch;
curlen+=ob.curlen;
if(!ch){cerr<<"out of memory!\n"; exit(1);}
strcpy(ch,temp);
strcat(ch,ob.ch);
delete[]temp;return *this;
}
char &String00::operator[](int i){
if(i<0&&i>=curlen)
{cout<<"Out Of Boundary! \n";exit(1);}
return ch[i];
}
int String00::Find(String00 & pat)const{
char *p=pat.ch,*s=ch;int i=0;
if(*p&&*s)
while(i<=curlen-pat.curlen)
if(*p++ == * s ++){
if(!*p) return i;
}
else{i++;s=ch+i;p=pat.ch;}
return -1;
}
int String00::count(String00 & pat){
if(this->Find(pat)!=-1)
{char *p=pat.ch,*s=ch;int i=0;int j=0;
if(*p&&*s)
while(i<=curlen-pat.curlen)
if(*p++ == * s ++){
if(!*p) j++; }
else{i++;s=ch+i;p=pat.ch;}
return j;
}
else return 0;
}
void main(int argc, char* argv[]){
int i=1;
int loc,len;
char str[20]="dfsabcdabste";
String00 obj(str);
cout<<obj.get()<<endl;
cout<<"the length of the string is "<<obj.length()<<endl;
cout<<"please input the location of the substring:"<<endl;
cin>>loc;
cout<<"please input the length of the substring:"<<endl;
cin>>len;
cout<<obj(loc,len).get()<<endl;
String00 obj1;
cout<<"now copy the original string"<<endl;
obj1=obj;
cout<<"the new string is "<<obj1.get()<<endl;
char sub[]="ab";
String00 obj2(sub);
cout<<"the letter 'ab'exist in the string?";
if(obj.Find(obj2)!=-1) cout<<"true"<<endl;
else cout<<"false"<<endl;
cout<<"'ab' appear in string "<<obj.count(obj2)<<" times"<<endl;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -