这个串的基本操作代码哪错了 啊?求指教
#include <iostream>using namespace std;
typedef struct{
char *ch;
int length;
}HString;
bool StrAssign(HString &T,char *chars);
int StrLength(HString S);
int StrCompare(HString S,HString T);
bool ClearString(HString &S);
bool Concat(HString &T,HString S1,HString S2);
HString SubString(HString S,int pos,int len);
bool StrInsert(HString &S,int pos,HString T);
void StrTraverse(HString S);
bool StrAssign(HString &T,char *chars)
{
int i;
char *c=chars;
if(T.ch)free(T.ch);
for(i=0;c;i++,++c);
if(!i){T.ch=NULL;T.length=0;}
else{
if(!(T.ch=(char *)malloc(i*sizeof(char))))
exit(0);
for(int j=0;j<i;j++)
T.ch[i]=chars[i];
T.length=i;
}
return true;
}
int StrLength(HString S)
{
return S.length;
}
int StrCompare(HString S,HString T)
{
for(int i=0;i<S.length&&i<T.length;i++)
if(S.ch[i]!=T.ch[i])return S.ch[i]-T.ch[i];
return S.length-T.length;
}
bool ClearString(HString &S)
{
if(S.ch){free(S.ch);S.ch=NULL;}
S.length=0;
return true;
}
bool Concat(HString &T,HString S1,HString S2)
{
if(T.ch)free(T.ch);
if(!(T.ch=(char *)malloc((S1.length+S2.length)*sizeof(char))))
exit(0);
for(int i=0;i<S1.length;i++)
T.ch[i]=S1.ch[i];
T.length=S1.length+S2.length;
for(int i=S1.length;i<T.length;i++)
T.ch[i]=S2.ch[i-S1.length];
return true;
}
bool SubString(HString &Sub,HString S,int pos,int len)
{
if(pos<1||pos>S.length||len<0||len>S.length-pos+1)
return false;
if(Sub.ch)free(Sub.ch);
if(!len){Sub.ch=NULL;Sub.length=0;}
else{
Sub.ch=(char *)malloc(len*sizeof(char));
for(int i=0;i<len;i++)
Sub.ch[i]=S.ch[i+pos-1];
Sub.length=len;
}
return true;
}
bool StrInsert(HString &S,int pos,HString T)
{
if(pos<1||pos>S.length)return false;
if(T.length){
if(!(S.ch=(char *)realloc(S.ch,(S.length+T.length)*sizeof(char))))
exit(0);
for(int i=S.length-1;i>=pos-1;i--)
S.ch[i+S.length]=S.ch[i];
for(int i=pos-1;i<pos+T.length-1;i++)
S.ch[i]=T.ch[i-pos+1];
}
return true;
}
void StrTraverse(HString S)
{
if(S.length){
for(int i=0;i<S.length;i++)
cout<<S.ch[i];
}
cout<<endl;
}
int main()
{
HString S1,S2,T,S,Sub;
StrAssign(S1,"welcome to computer");
StrAssign(S2,"I like Date Structers!");
StrAssign(T,"C++");
cout<<"S1:";
StrTraverse(S1);
cout<<"the length is "<<StrLength(S1)<<endl;
cout<<"S2:";
StrTraverse(S2);
cout<<"the length is "<<StrLength(S2)<<endl;
cout<<"T:";
StrTraverse(T);
cout<<"the length is "<<StrLength(T)<<endl;
if(StrCompare(S1,S2)>0)cout<<"S1>S2";
else
if(StrCompare(S1,S2)<0)cout<<"S1<S2";
else
cout<<"S1=S2";
cout<<endl;
Concat(S,S1,S2);
cout<<"S:";
StrTraverse(S);
StrInsert(S1,6,T);
cout<<"new S1:";
StrTraverse(S1);
SubString(Sub,S2,3,5);
cout<<"Sub:";
StrTraverse(Sub);
return 0;
}