说明:
1 用堆分配存储结构存放字符串。
2 类型定义和主函数不能修改,补足需要的函数。
3 函数的功能在提供的文本中说明
运行结果:
ahebhechedhe
he
hello!
ahello!bhello!chello!dhello!
#include
#include
#include
//#define MAXSTRLEN 255
#define OK 1
#define ERROR 0
#define OVERFLOW 0
typedef int Status;
typedef struct{
char *ch;
int length;
}HString;
Status StrAssign(HString &S,char *chars)
{
int i,j;
char *c;
if(S.ch) free(S.ch);
for(i=0,c=chars;*c;i++,c++);
if(!i){S.ch=NULL;S.length=0;}
else{
if(!(S.ch=(char*)malloc(i*sizeof(char)))) exit(OVERFLOW);
for(j=0;j //S.ch[0...]=chars[0...];
S.length=i;
}
return OK;
}//串赋值
void Display_String(HString S)
{ int i;
for(i=0;i
}//串显示
int Index(HString S, HString T,int Pos)
{
int i,j;
i=Pos-1;j=0;
while(i
else{i=i-j+1;j=0;}
}
if(i
} //在串S中扫描子串T的位置值,如不存在子串T返回0
void Delete(HString &S,int pos,int len)
{
HString L;
int i;
if(!(L.ch=(char*)malloc((S.length-len)*sizeof(char)))) exit(0);
for(i=0;i
for(;i
free(S.ch);
S=L;
} //在串S中删去从pos位置开始的len个字符
void Insert(HString &S,int pos,HString T)
{
HString L;
int i;
if(!(L.ch=(char*)malloc((S.length+L.length)*sizeof(char)))) exit(0);
for(i=0;i
free(S.ch);
S=L;
}//在串S的pos位置插入子串T
void Replace_SubString(HString &S, HString T1,HString T2)
{ int Pos,len;
len=T1.length;
for(Pos=1;Pos
Delete(S,Pos,len);
Insert(S,Pos,T2);
Pos+=T2.length;
}
}//通过对Index、Delete和Insert函数的调用,完成将串S中出现的子串T1用串T2替代
void main(){
HString S,T1,T2;
StrAssign(S,"ahebhechedhe");
Display_String(S);
cout<
Display_String(T1);
cout<
Display_String(T2);
cout<
Display_String(S);
}