【C/C++】将一个字符串插入至另一个源字符串的某个位置

将一个字符串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 main()
{
    char str1[100];
    char str2[100];
    char end[100]={0};
    char x;
    printf("Input source string 1:\n");
    gets(str1);
    printf("Input inserted string 2:\n");
    gets(str2);
    printf("Input a letter to locate the index:\n");
    scanf("%c",&x);
    int i=0,j=0,flag=0;
    int index=0;
    while(str1[i]!='\0')
    {
        if(str1[i]==x)
        {
            flag++;
            index=i;
            break;
        }
        i++;
    }
    i=0;
    if(flag)
    {
        for(int z=0;z<index;z++)
        {
            end[i]=str1[i];
            i++;
        }
        for(int z=0;z<strlen(str2);z++)
        {
            end[i]=str2[z];
            i++;
        }
        for(int z=index;z<strlen(str1);z++)
        {
            end[i]=str1[z];
            i++;
        }
        printf("The new string is:%s",end);
    }
    else
        printf("Not found!");
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值