C语言习题:将一个字符串插入至另一个源字符串的某个位置

这篇文章介绍了如何使用C语言编写一个程序,通过用户输入的源字符串、待插入字符串和要查找的字符,在源字符串中找到该字符的第一个出现位置并插入新串。如果字符未找到,则输出Notfound!。
摘要由CSDN通过智能技术生成

题目:将一个字符串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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值