发布网友 发布时间:2022-04-29 22:54
共1个回答
热心网友 时间:2022-06-25 03:23
希望下面这个程序符合你的要求,呵呵#include<iostream>#include<malloc.h>#define OK 1#define ERROR 0using namespace std;typedef struct{ char *ch; int length; //串的长度}HString;//========= int StrAssign(HString &T){//生成一个串常量 int j; cout<<"请输入串T的长度:"<<endl; cout<<"T.length="; cin>>T.length; cout<<"请输入串:"<<endl; if(!T.length){T.ch=NULL;T.length=0;} else{ if(!(T.ch=(char*)malloc(T.length*sizeof(char)))) return ERROR; for(j=0;j<T.length;j++) cin>>T.ch[j]; } return OK;} //串的链接======= int Concat(HString &T){ int i,j; HString S1; HString S2; if(T.ch) free(T.ch); StrAssign(S1); StrAssign(S2); if(!(T.ch=(char*)malloc((S1.length+S2.length)*sizeof(char)))) return ERROR; for(i=0;i<S1.length;i++) T.ch[i]=S1.ch[i]; T.length=S1.length+S2.length; for(i=S1.length,j=0;i<T.length,j<S2.length;i++,j++) T.ch[i]=S2.ch[j]; return OK;} //串的插入======== int StrInsert(HString &T) //在串的T第pos个字符之前插入串S{ int i,j,k,pos; HString S; cout<<"请输入串S的长度:"; cin>>S.length; cout<<"请输入串S:"<<endl; if(!(S.ch=(char*)malloc(S.length*sizeof(char)))) return ERROR; for(i=0;i<S.length;i++) cin>>S.ch[i]; cout<<"请输入插入的位置:"; cin>>pos; if(pos<1||pos>T.length+1) return ERROR; if(S.length) { if(!(T.ch=(char*)realloc(T.ch,(T.length+S.length)*sizeof(char)))) return ERROR; for(i=T.length-1;i>=pos-1;i--) T.ch[i+S.length]=T.ch[i]; for(j=pos-1,k=0;j<=pos+S.length-2,k<S.length;j++,k++) T.ch[j]=S.ch[k]; T.length+=S.length; } return OK;} //串的输出========== void print(HString &T){ int i; for(i=0;i<T.length;i++) cout<<" "<<T.ch[i];} //主函数=========== void main(){ cout<<"=============串的堆分配存储表示=============="<<endl; HString T; StrAssign(T); cout<<"您输入有效串为:"<<endl; print(T); cout<<endl; cout<<"==========串连接操作=========="<<endl<<endl; Concat(T); cout<<"连接后的串为:"<<endl; print(T); cout<<endl; cout<<"==========串插入操作=========="<<endl<<endl; StrInsert(T); cout<<"插入后的串为:"<<endl; print(T); cout<<endl; }