69,371
社区成员
发帖
与我相关
我的任务
分享
//从键盘接收两个字符串S和t。
//1、输出S和t的长度 。
//2、从键盘接收一个n(0或正整数),并且在串S的第n个字符位置插入串t;输出S的长度。
//3、采用简单匹配算法求出t在S中的位置。
#include <stdio.h>
#include <string.h>
#define MAXLEN 1000
char S[MAXLEN*2];
char t[MAXLEN];
int n;
void main() {
printf("Input string S:");
fgets(S,MAXLEN,stdin);
S[strlen(S)-1]=0;
printf("Input string t:");
fgets(t,MAXLEN,stdin);
t[strlen(t)-1]=0;
printf("strlen(S)=%d,strlen(t)=%d\n",strlen(S),strlen(t));
while (1) {
printf("Input n(0<=n<=%d):",strlen(S));
scanf("%d",&n);
if (0<=n && n<=(int)strlen(S)) break;
}
memmove(S+n+strlen(t),S+n,strlen(S)-n+1);
memmove(S+n ,t ,strlen(t) );
printf("After insert t at %d in S, S=[%s], strlen(S)=%d\n",n,S,strlen(S));
printf("Use strstr found t at %d in S.\n",strstr(S,t)-S);
}
//C:\tmp>insert
//Input string S:abcdefg
//Input string t:123
//strlen(S)=7,strlen(t)=3
//Input n(0<=n<=7):0
//After insert t at 0 in S, S=[123abcdefg], strlen(S)=10
//Use strstr found t at 0 in S.
//
//C:\tmp>insert
//Input string S:abcdefg
//Input string t:1234
//strlen(S)=7,strlen(t)=4
//Input n(0<=n<=7):3
//After insert t at 3 in S, S=[abc1234defg], strlen(S)=11
//Use strstr found t at 3 in S.
//
//C:\tmp>insert
//Input string S:abcdefg
//Input string t:12
//strlen(S)=7,strlen(t)=2
//Input n(0<=n<=7):7
//After insert t at 7 in S, S=[abcdefg12], strlen(S)=9
//Use strstr found t at 7 in S.
//
//C:\tmp>insert
//Input string S:abcdefg
//Input string t:bc
//strlen(S)=7,strlen(t)=2
//Input n(0<=n<=7):5
//After insert t at 5 in S, S=[abcdebcfg], strlen(S)=9
//Use strstr found t at 1 in S.