题目如下:
将一个字符串插入至另一个源字符串的某个位置: 将一个字符串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>
int Find(char a[],char b[],char temp,int n,int m);
int main()
{
int len1,len2,flag;
char a[50],b[50],temp;
printf("Input source string 1:\n");
gets(a);
printf("Input inserted string 2:\n");
gets(b);
printf("Input a letter to locate the index:\n");
scanf(" %c",&temp);
len1=strlen(a);
len2=strlen(b);
flag=Find(a,b,temp,len1,len2);
if(flag)
{
printf("The new string is:%s",a);
}
if(!flag)
{
printf("Not found!");
}
}
int Find(char a[],char b[],char temp,int n,int m)
{
for(int i=0;i<n;i++)
{
if(a[i]==temp)
{
for(int j=m+n-1,k=n-i+1;j>=n-i+1;j--,k--)
{
a[j]=a[k];
}
for(int j=i,k=0;j<i+m;j++,k++)
{
a[j]=b[k];
}
a[m+n]='\0';
return 1;
}
}
return 0;
}
欢迎交流