动态拼接字符串

   ❤️强烈推荐人工智能学习网站❤️    

  工作中有时候需要传入不定个数的字符串,就需要专门写一个函数动态添加字符串,下面看下函数:

#include <iostream>
#include <cstring>
#include "stdarg.h"

std::string append(int count,const char* msg, ...){
    std::string srcStr;
    va_list vaList;
    va_start(vaList, msg);
    char tmp[1024] = {0};
    int n = 0;
    int true_count = count -1;
    strcat(tmp,msg);

    while(1)
    {
        strcat(tmp,"_");
        strcat(tmp,va_arg(vaList,char*));

        n++;
        if(n == true_count)
        {
            printf("%d\n",n);
            break;
        }
    }
    va_end(vaList);//结束可变参数列表
    std::string stmp(tmp);
    srcStr += stmp;

    return srcStr;
}

int main(){
    //string
    std::string str1 = "12";
    std::string str2 = "34";
    std::string str3 = "56";
    std::string src = append(3,str1.c_str(),str2.c_str(),str3.c_str());

    std::cout <<  src << std::endl;

    return 0;
}

经测试好用。

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

盼盼编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值