第四次编程练习:字符串编程,将字符串S中出现的子串T1用字符串T2替代。

说明:

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   cout< }
}//串显示

int Index(HString S, HString T,int Pos)
{
 int i,j;
 i=Pos-1;j=0;
 while(i  if(S.ch[i]==T.ch[j]){++i;++j;}
  else{i=i-j+1;j=0;}
 }
 if(i else return 0;
 } //在串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 i+=len;
 for(;i L.length=S.length-len;
 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   for(;i   for(i=0;i   L.length=S.length+T.length;
   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   {Pos=Index(S,T1,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<StrAssign(T1,"he");
Display_String(T1);
cout<StrAssign(T2,"hello!");
Display_String(T2);
cout<Replace_SubString(S,T1,T2);
Display_String(S);
}



你可能感兴趣的:(数据结构)