设计函数char *insert(s1, s2, n),用指针实现在字符串s1中的指定位置n处插入字符串s2,s1字符串有足够的空间存放s2字符串。

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

void insert(char* s1, char* s2, char* s, int n)
{
    int idx = 0;
    for (int i = 0; i < strlen(s1); i++)
    {
        if (i == n)
        {
            for (int j = 0; j < strlen(s2); j++)
            {
                s[idx] = s2[j];
                idx++;
            }
        }
        s[idx] = s1[i];
        idx++;
    }
    s[idx] = '\0';
}
int main()
{
    int idx = 0;
    char a[1000];
    char b[1000];
    char s[1000];
    printf("请输入第一个字符串:");
    gets_s(a);
    printf("请输入第二个字符串:");
    gets_s(b);
    printf("请输入插入的位置:");
    scanf("%d", &idx);
    char* m = a;
    char* n = b;
    char* o = s;
    insert(m, n, o, idx);
    printf("%s", s);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是用指针编写的C语言函数insert(s1,s2,f)的代码: ```c #include <stdio.h> #include <string.h> void insert(char *s1, char *s2, int f) { int len1 = strlen(s1); int len2 = strlen(s2); char temp[len1 + len2 + 1]; // 临时数组,存放插入后的结果 // 拷贝s1f之前的部分到temp数组 strncpy(temp, s1, f - 1); temp[f - 1] = '\0'; // 拼接s2到temp数组 strcat(temp, s2); // 拼接s1f之后的部分到temp数组 strcat(temp, s1 + f - 1); // 将temp数组的结果拷贝到s1 strcpy(s1, temp); } int main() { char s1[100] = "hello world"; char s2[20] = "beautiful "; int f = 6; insert(s1, s2, f); printf("%s", s1); // 输出:hello beautiful world return 0; } ``` 在函数,我们首先通过strlen()函数获取s1s2的长度,然后创建一个临时数组temp,它的长度为s1s2长度之和再加1,因为我们需要在temp数组加上一个字符串结束符'\0'。 接着,我们将s1f之前的部分拷贝到temp数组,使用strncpy()函数,它的第三个参数是拷贝的字符数,因此,我们需要拷贝f-1个字符。然后,我们在temp数组拼接s2,使用strcat()函数,将s2直接拼接在temp数组的'\0'。最后,我们将s1f之后的部分拼接到temp数组,同样使用strcat()函数,第二个参数是s1+f-1,表示从s1的第f个字符开始拼接。 最后,我们将temp数组的结果拷贝回s1,使用strcpy()函数。 在main()函数,我们定义了一个字符串s1和一个字符串s2,并且定义了一个整数f表示要插入位置。然后,我们调用insert()函数,将s2插入s1的第f个字符之前。最后,我们输出s1的结果,即插入后的字符串

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值