c++拼接多个字符串

通过字符串流来完成字符串和数字的拼接,再将字符串流的内容转化为string的类型。

使用ostringstream之前,需要指定头文件:

#include <iostream>
#include <vector>
#include <sstream>

using namespace std;
void SplitString(const string&, vector<string>&, const string&);

int main()
{
    ostringstream oss;
    vector<string> data;
    string value = "30,45,22,34,56,99";
    SplitString(value,data,",");
    for(int i = 0;i != data.size();i++)
    {
        cout << data[i] << " ";
    }
    cout << endl;

    for(int i = 0;i != data.size();i++)
    {
        oss << data[i] << ",";
    }
    cout << oss.str() << endl;
    return 0;
}

void SplitString(const string& s, vector<string>& v, const string& c)
{
     string::size_type pos1, pos2;
     pos2 = s.find(c);
     pos1 = 0;
     while(string::npos != pos2)
     {
         v.push_back(s.substr(pos1, pos2-pos1));

         pos1 = pos2 + c.size();
         pos2 = s.find(c, pos1);
     }
     if(pos1 != s.length())
         v.push_back(s.substr(pos1));
}
 

原博:https://blog.csdn.net/qq_38410730/article/details/103272396?utm_medium=distribute.pc_relevant.none-task-blog-title-10&spm=1001.2101.3001.4242

C++中,将多个字符串拼接到一起可以通过多种方式实现。最常用的方法之一是使用`std::string`类的`+=`操作符,或者使用`std::string`类提供的`append()`方法。以下是两种常见的字符串拼接方式: 1. 使用`+=`操作符: ```cpp #include <iostream> #include <string> int main() { std::string str1 = "Hello"; std::string str2 = "World"; str1 += str2; // 拼接str2到str1后面 std::cout << str1 << std::endl; // 输出结果是 "HelloWorld" return 0; } ``` 2. 使用`append()`方法: ```cpp #include <iostream> #include <string> int main() { std::string str1 = "Hello"; std::string str2 = "World"; str1.append(str2); // 使用append方法拼接str2到str1后面 std::cout << str1 << std::endl; // 输出结果是 "HelloWorld" return 0; } ``` 在C++11及更高版本中,还可以使用`+`操作符直接拼接字符串: ```cpp #include <iostream> #include <string> int main() { std::string str1 = "Hello"; std::string str2 = "World"; std::string result = str1 + str2; // 直接拼接 std::cout << result << std::endl; // 输出结果是 "HelloWorld" return 0; } ``` 此外,如果要频繁地进行字符串拼接,尤其是拼接大量的字符串,使用`std::ostringstream`可能会更加高效,因为它可以避免多次重新分配内存: ```cpp #include <iostream> #include <string> #include <sstream> int main() { std::ostringstream oss; oss << "Hello" << " " << "World"; std::string result = oss.str(); // 获取拼接后的字符串 std::cout << result << std::endl; // 输出结果是 "Hello World" return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值