题目:将一个字符串2插入到源字符串1中 第一次出现某字符的位置,并打印出形成的新串。
如果 字符串1中找不到输入的字符, 则显示“Not found!”并结束程序。
注:源字符串长度及待插入字符串长度不超过50
提示信息:
printf("Input source string 1:\n")
printf("Input inserted string 2:\n")
printf("Input a letter to locate the index:\n")
输出信息格式:
printf("The new string is:%s")
printf(“Not found!”)
测试样例1:
输入信息:
Input source string 1:
abcdecfg
Input inserted string 2:
*-*-*-*
Input the a letter to locate the index:
c
输出结果:
The new string is:ab*-*-*-*cdecfg
测试样例2:
输入信息:
Input source string 1:
abcdecfg
Input inserted string 2:
****
Input the a letter to locate the index:
h
输出结果:
Not found!
按照常规做法,应该是将字符串缝合到一起,然后再输出。
不过我有个新的想法,仅供参考,如果有错误请指出,谢谢!
#include <stdio.h>
#include <string.h>
#define N 50
int main()
{
int i,j,count=-1;
char s1[N],s2[N],flag;
printf("Input source string 1:\n");
gets(s1);
printf("Input inserted string 2:\n");
gets(s2);
printf("Input a letter to locate the index:\n");
scanf("%c",&flag);
for (i=0;i<N;i++)
{
if (s1[i]==flag)
{
count=i;
break;
}
}
if (count>=strlen(s1)&&count<0) printf("Not found!");
else
{
printf("The new string is:");
for (i=0;i<=count-1;i++)
{
printf("%c",s1[i]);
}
for (i=0;i<=strlen(s2);i++)
{
printf("%c",s2[i]);
}
s1[strlen(s1)+strlen(s2)]='\0';
for (i=count;i<=strlen(s1);i++)
{
printf("%c",s1[i]);
}
}
return 0;
}