Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate strings with space into one string with STL in c++ [duplicate]

Tags:

c++

stl

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;
}
like image 710
q0987 Avatar asked Mar 21 '23 01:03

q0987


2 Answers

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();
like image 169
Gabriel L. Avatar answered Mar 23 '23 16:03

Gabriel L.


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; });
like image 26
Dietmar Kühl Avatar answered Mar 23 '23 14:03

Dietmar Kühl