函数void Insert(char *s, char *t, int pos)将字符串t插入到字符串s中,插入的位置为pos。【数据结构】

编写函数实现以下功能,并要求测试。

函数void Insert(char *s, char *t, int pos)将字符串t插入到字符串s中,插入的位置为pos。(不得使用库函数)

提示,插入过程中,需要考虑字符串s空间是否足够。如果不足够,需要重新分配更大的空间。


 

输出结果: 

 


主要算法: 


void Insert(char *a, char *b, int pos)
{
    int i, len1 = 0, len2 = 0;
    while (a[len1] != '\0')
        len1++;               \
    while (b[len2] != '\0')
        len2++;                         
    for (i = len1 - 1; i >= pos - 1; i--)     
        a[i + len2] = a[i];
    for (i = pos - 1; i < pos - 1 + len2; i++)
        a[i] = b[i - pos + 1];     
    len1 += len2;               
    a[len1] = '\0';               
    for (i = 0; i < len1; i++)
        cout << a[i];
    cout << endl;
}

 


完整代码: 

#include<iostream>
using namespace std;
void Insert(char *a, char *b, int pos);
int main()
{
        char a[200], b[100];
        cout << "请输入字符串a:";
        cin >> a;
        cout << "请输入字符串b:";
        cin >> b;
        int pos;
        cout << "输入你要插入的位置:";
        cin >>pos;
        Insert(a, b, pos);
    return 0;
}
void Insert(char *a, char *b, int pos)
{
    int i, len1 = 0, len2 = 0;
    while (a[len1] != '\0')
        len1++;               \
    while (b[len2] != '\0')
        len2++;                         
    for (i = len1 - 1; i >= pos - 1; i--)     
        a[i + len2] = a[i];
    for (i = pos - 1; i < pos - 1 + len2; i++)
        a[i] = b[i - pos + 1];     
    len1 += len2;               
    a[len1] = '\0';               
    for (i = 0; i < len1; i++)
        cout << a[i];
    cout << endl;
}

 

  • 8
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值