本博文源于严书的《数据结构》,旨在用c++来编写这周课后习题代码,本周的任务是写一道算法题。题目难点在于不能使用库函数,接口定死了,因此解决步骤六行代码
题目再现
完成P109算法设计题第(3)题的算法设计与实现,并编写程序进行验证
分析步骤
求length,插入法移动位置,最后移动,得到答案。
实验效果
完整效果
#include<iostream>
#include<cstring>
using namespace std;
void insert(char *s,char *t,int pos){
int Slen =-1,Tlen=-1;
while(s[++Slen]!='\0');//获得主串长
while(t[++Tlen]!='\0'); //获得子串长
for(int i = Slen-1;i>=pos-1;i--) s[i+Tlen]=s[i]; //移动s长度
for(int i =pos-1,cnt=0;cnt<Tlen;i++,cnt++) s[i] = t[i-pos+1]; //在s串插入t串
s[Slen+Tlen]='\0'; //c语言风格收尾
}
int main(){
char s[256]="abcfg";
char t[3] = "de";
cout << s << endl << t << endl << "Insert 4 position:" << endl;
insert(s,t,4);
cout << s << endl;
return 0;
}