C语言在字符串指定位置插入新的字符串

本文介绍了如何在C语言中使用getchar和scanf函数获取用户输入,以及strcat函数实现两个字符数组的连接,最终输出合并后的字符串‘abcdef’。
/*
 input:
 abcdef
 abc
 3

 output:
 abcabcdef
 */


#include <stdio.h>
#include <string.h>

#define  L 100

void addChar(char *,char *,int);

int main()
{
    char str1[L+1],str2[L+1],ch;
    int i=0,j=0,a;
    while ((ch=getchar())!='\n'&&ch!=EOF)
    {
        str1[i++]=ch;
    }
    str1[i]='\0';
    while ((ch=getchar())!='\n'&&ch!=EOF)
    {
        str2[j++]=ch;
    }
    str2[j]='\0';
    scanf("%d",&a);
    addChar(str1,str2,a);
    printf("%s",str1);
    return 0;
}

void addChar(char *str1,char *str2,int a)
{
    char *p1=str1;
    p1+=a;//p1指向了abcdef中的d
    strcat(str2,p1);//abc->abcdef
    *p1='\0';
    strcat(str1,str2);//abc+abcdef->abcabcdef
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值