4

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;
}
q0987
  • 34,938
  • 69
  • 242
  • 387

3 Answers3

4

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; });
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
3

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();
Gabriel L.
  • 4,678
  • 5
  • 25
  • 34
2

You can use std::ostream_iterator.

std::vector< std::string > vs{ "one", "two", "three" };

std::ostringstream result_stream;
std::ostream_iterator< std::string > oit( result_stream, " " );
std::copy( vs.begin(), vs.end(), oit );

std::string result = result_stream.str();

http://ideone.com/VfxWbd

If you want the result in a string, use std::ostringstream for the output iterator.

PolGraphic
  • 3,233
  • 11
  • 51
  • 108
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
  • Trailing space needs to be trimmed when `vs` is empty – P0W Jan 08 '14 at 03:14
  • @P0W How can you specify a requirement on someone else's question? Anyway just refer to the answer of the duplicate Q&A, which removes trailing space if the result is *not* empty. – Potatoswatter Jan 08 '14 at 06:59