合并两个字符串

该博客介绍了一个C++函数,用于合并两个字符串而不改变原始字符串。通过计算字符串长度,动态分配内存,然后逐字符复制到新分配的空间中,最后返回合并后的字符串。在主函数中,展示了如何使用这个函数并释放内存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将两个字符串连接,不破坏原有字符串

#include<stdio.h>
#include<iostream>

using namespace std;

char* consent(char*s1, char*s2)
{
    int len1, len2, len;
    char *s;

    len1 = strlen(s1);
    len2 = strlen(s2);
    len = len1 + len2;
    s = (char*)malloc(len*sizeof(char));  //必须得先申请地址
    int i;
    for (i = 0; i < len1; i++)
        s[i] = s1[i];
    for (i = 0; i < len2; i++)
        s[len1 + i] = s2[i];
    s[len - 1] = '\0';
    return s;
}

void delety(char*s)
{
    free(s);                     //不清楚这样释放内存对不对
    cout << "free" << endl;
}

int main()
{
    char s1[] = "this is a test ";
    char s2[] = "for connecting two string.";
    char *s;
    s = consent(s1, s2);
    cout << s1 << endl;
    cout << s2 << endl;
    cout << consent(s1, s2) << endl;
    delety(s);
    return 0;

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值