实战c++中的string系列--std:vector 和std:string相互转换(vector to stringstream)
string、vector 互转
string 转 vector
vector vcBuf;
string stBuf("Hello DaMao!!!");
----------------------------------------------
vcBuf.resize(stBuf.size());
vcBuf.assign(stBuf.begin(), stBuf.end());
vector 转 string
stBuf.clear();
stBuf.assign(vcBuf.begin(), vcBuf.end());
有时候也会遇到std:vector与转std:string 相互转换的情况。
首先看一下vector<char>
如何转string:
std::vector<char> *data = response->getResponseData();
std::string res;
//方法一
for (int i = 0;i<data->size();++i) {
res+=(*data)[i];
}
res+='\0';
std:cout << res;
//方法二
std::vector<char> *data = response->getResponseData();
std::string res;
res.insert(res.begin(), data->begin(), data->end());
std::cout << res;
//方法三
std::vector<char> *data = response->getResponseData();
std::string res;
const char* s = &(*data->begin());
res = std::string(s, data->size());
std::cout << res;
//方法四
string ch = "what a fucking day!";
vector <char> ta;
ta.resize(ch.size());
ta.assign(ch.begin(),ch.end());
string 转vector就会更容易:
vector <char> ta = {‘a’, 'b', 'c'};
ch.clear();
ch.assign(ta.begin(),ta.end());
================================================================
vector to stringstream
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <iterator>
// Dummy std::vector of strings
std::vector<std::string> sentence;
sentence.push_back("aa");
sentence.push_back("ab");
// Required std::stringstream object
std::stringstream ss;
// Populate
std::copy(sentence.begin(), sentence.end(),std::ostream_iterator<std::string>(ss,"\n"));
// Display
std::cout<<ss.str()<<std::endl;