串的基本操作
#include "stdio.h"#include "stdlib.h"
#define OVERFLOW -2
#define NULL 0
#define ERROR 0
typedef struct
{
char *ch;
int length;
}hstring;
void strassign(hstring *T,char *cha)
{
int i,j; char *c;
if(T->ch) free(T->ch);
for(i=0,c=cha;*c!='\0';++i,++c);
if(!i) {T->ch=NULL;T->length=0;}
else
{ T->ch=(char *)malloc(i*sizeof(char));
if(!T->ch) exit(OVERFLOW);
for(j=0;j<=i-1;j++)
{*(T->ch+j)=*(cha+j);}
T->length=i;
}
}
void print_string(hstring *L)
{
int i;
for(i=0;i<L->length;i++)
{
putch(L->ch[i]);
}
}
int strlength(hstring *S,char *char1)
{
int i; char *c;
for(i=0,c=char1;*c!='\0';i++,c++);
S->length=i;
return S->length;
}
void concat(hstring *M,hstring *T,hstring *S)
{ int i,j;
if(M->ch) free(M->ch);
M->ch=(char *)malloc((T->length+S->length)*sizeof(char));
if(!M->ch) exit(OVERFLOW);
for(i=0;i<T->length;i++)
M->ch[i]=T->ch[i];
M->length=T->length+S->length;
for(i=T->length,j=0;i<M->length,j<S->length;i++,j++)
M->ch[i]=S->ch[j];
}
void substring(hstring *R,hstring *T,int pos,int len)
{ int i,j;
if(pos<1 || pos>T->length || len<0 || len>T->length-pos+1)
{ printf("data error!");
return ERROR;}
if(R->ch) free(R->ch);
if(!len){R->ch=NULL; R->length=0;} /*null string*/
else
{
R->ch=(char *)malloc(len*sizeof(char));
for(i=0,j=pos-1;i<len,j<=pos+len-2;i++,j++)
{ R->ch[i]=T->ch[j];}
R->length=len;
}
}
main()
{ char chars[20]; char char1[20];
int l;
hstring *T,*S,*M,*R;
clrscr();
printf("please input the string chars:\n");
gets(chars);
strassign(T,chars);
printf("please input the string char1:\n");
gets(char1);
strassign(S,char1);
printf("the string T is:\n");
print_string(T);
printf("\nthe string S is:\n");
print_string(S);
l=strlength(S,char1);
printf("\nthe length of string S is: %d",l);
concat(M,T,S);
printf("\nthe concat's string M is:\n");
print_string(M);
substring(R,T,2,3);
printf("\nthe substring R is:\n");
print_string(R);
getch();
}
(怎么这个程序第一次运行自动关闭啊,接着后面的运行就正确了啊!!!!)