|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <malloc.h>
#define MAXLEN 20
typedef struct
{
char ch[MAXLEN];
int len;
}SString;
int StrInsert(SString *s,int pos,SString *t)//串的插入
{
int i;
if(pos<0||pos>s->len)
return 0;
if(s->len+t->len<=MAXLEN)
{
for(i=s->len+t->len-1;i>=t->len+pos;i--)
s->ch[i]=s->ch[i-t->len];
for(i=0;i<t->len;i++)
s->ch[i+pos]=t->ch[i];
s->len=s->len+t->len;
s->ch[s->len]='\0';
}
else if(pos+t->len<=MAXLEN)
{
for(i=MAXLEN;i>t->len+pos-1;i++)
s->ch[i]=s->ch[i-t->len];
for(i=0;i<t->len;i++)
s->ch[i+pos]=t->ch[i];
s->len=MAXLEN;
s->ch[s->len]='\0';
}
else
{
for(i=0;i<MAXLEN-pos;i++)
s->ch[i+pos]=t->ch[i];
s->len=MAXLEN;
s->ch[s->len]='\0';
}
return 1;
}
int StrDlete(SString *s,int pos,int len)//串的删除
{
int i;
if(pos<0||pos>s->len-len)
return 0;
for(i=pos+len;i<s->len;i++)
s->ch[i-len]=s->ch[i];
s->len=s->len-len;
s->ch[s->len]='\0';
return 1;
}
SString * InitStr(SString *s)//串的出始化
{
s=(SString *)malloc(sizeof(SString));
s->len=NULL;
return s;
}
SString *StrCreat(SString *s)//串的建立
{
char ch;
printf("请输入字符串,按回车结束:\n");
while((ch=getchar())!='\n')
{
s->ch[s->len]=ch;
s->len++;
}
s->ch[s->len]='\0';
return s;
}
void print (SString *s)//串的输出
{
printf("%s\n",s->ch);
}
int main()
{
SString *s,*t;
int pos1,pos2,len;
s=InitStr(s);
s=StrCreat(s);
printf("插入的串:\n");
t=InitStr(t);
t=StrCreat(t);
printf("插入位置:");
scanf("%d",&pos1);
StrInsert(s,pos1,t);
printf("插入后的串为:");
print(s);
printf("删除位置:");
scanf("%d",&pos2);
printf("删除长度:");
scanf("%d",&len);
StrDlete(s,pos2,len);
print(s);
return 0;
}
求大神完善算法,该算法能运行,但有警告
给个建议:
与其苦等别人改代码,不如好好参考、对比网上的相关代码~
|
|