C# · 12月 20, 2021

【数据结构】顺序串的插入算法,删除算法,连接运算,顺序串求子串算法

主函数自行添加

头文件 + 宏定义

#include

#include

#define MAXSIZE 100

串的顺序存储

typedef struct

{

char str[MAXSIZE];

int length;

}seqstring;

顺序串的创建

void creat(seqstring *S)

{

char c;

int i=0;

while((c=getchar())!=’n’)

{

S->str[i++]=c;

}

S->str[i]=”;

S->length=i;

return ;

}

(1)插入运算

将字符串T插入到字符串S的第i个字符开始的位置上

void strinsert(seqstring *S,int i,seqstring T)

{

int k;

if(iS->length+1 || S->length + T.length>=MAXSIZE)

{

printf(“can not insertn”);

return ;

}

for(k=S->length-1;k>=i-1;k–)

{

S->str[k+T.length]=S->str[k];

}

for(k=0;k<T.length;k++)

{

S->str[k+i-1]=T.str[k];

}

S->length+=T.length;

S->str[S->length]=”;

}

(2)删除运算

将串S中从第i个字符起长度为len的字串删除

void strdelete(seqstring *S,int len)

{

int k;

if(iS->length || i+len-1>MAXSIZE)

{

printf(“can not deleten”);

return ;

}

for(k=i-1;klength-1;k++)

{

S->str[k]=S->str[k+len];

}

S->length-=len;

S->str[k]=”;

return ;

}

(3)顺序串的连接

将串S1和串S2连接

seqstring *strconcat(seqstring S,seqstring T)

{

int i;

seqstring *r;

if(S.length+T.length>=MAXSIZE)

{

printf(“can not concaten”);

return NULL;

}

r=(seqstring*)malloc(sizeof(seqstring));

for(i=0;i<S.length;i++)

{

r->str[i]=S.str[i];

}

for(i=0;i<T.length;i++)

{

r->str[S.length+i]=T.str[i];

}

r->length=S.length+T.length;

r->str[r->length]=”;

return r;

}

(4)求子串运算

从串第i个字符开始取长度为len的子串返回

seqstring *substring(seqstring S,int len)

{

int k;

seqstring *r;

if(iS.length || i+len-1>S.length)

{

printf(“substring errorn”);

exit(1);

}

else

{

r=(seqstring*)malloc(sizeof(seqstring));

for(k=0;k<len;k++)

{

r->str[k]=S.str[i-1+k];

}

r->length=len;

r->str[r->length]=”;

}

return r;

}