Given a vector of string ["one", "two", "three"].
Question> How do I convert it into "one two three"?
I know the manual way to do it with a loop and would like to know whether there is a simpler way with STL function.
// Updated based on suggestion that I should use accumulate
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
struct BindTwoStrings
{
string operator()(const string& s1, const string& s2) const {
return s1.empty() ? s2 : s1 + " " + s2;
}
};
int main()
{
vector<string> vecString {"one", "two", "three"};
string ret2;
ret2 = accumulate(vecString.begin(), vecString.end(), ret2,
[] (const string& s1, const string& s2) -> string {
return s1.empty() ? s2 : s1 + " " + s2; });
cout << "ret2:\"" << ret2 << "\"" << endl;
string ret;
ret = accumulate(vecString.begin(), vecString.end(), ret, BindTwoStrings());
cout << "ret:\"" << ret << "\"" << endl;
return 0;
}
With a std::stringstream
, you could do that :
std::stringstream ss;
const int v_size = v.size();
for(size_t i = 0; i < v_size; ++i) // v is your vector of string
{
if(i != 0)
ss << " ";
ss << v[i];
}
std::string s = ss.str();
You could use std::accumulate()
:
std::string concat = std::accumulate(std::begin(array) + 1, std::end(array), array[0],
[](std::string s0, std::string const& s1) { return s0 += " " + s1; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With