Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implode a vector of strings into a string (the elegant way)

I'm looking for the most elegant way to implode a vector of strings into a string. Below is the solution I'm using now:

static std::string& implode(const std::vector<std::string>& elems, char delim, std::string& s) {     for (std::vector<std::string>::const_iterator ii = elems.begin(); ii != elems.end(); ++ii)     {         s += (*ii);         if ( ii + 1 != elems.end() ) {             s += delim;         }     }      return s; }  static std::string implode(const std::vector<std::string>& elems, char delim) {     std::string s;     return implode(elems, delim, s); } 

Is there any others out there?

like image 241
ezpresso Avatar asked Apr 16 '11 19:04

ezpresso


People also ask

How do you concatenate a vector in a string?

Method 1: Using paste() paste() function is used to combine strings present in vectors passed to it an argument. Parameter: vectors are the input vectors to be concatenate. sep is the separator symbol that separates the strings present in the vector.

How do you pushback a vector in a string?

The push_back() member function is provided to append characters. Appends character c to the end of the string, increasing its length by one. Syntax : void string:: push_back (char c) Parameters: Character which to be appended.

Can a vector hold strings?

Conclusion: Out of all the methods, Vector seems to be the best way for creating an array of Strings in C++.


1 Answers

Use boost::algorithm::join(..):

#include <boost/algorithm/string/join.hpp> ... std::string joinedString = boost::algorithm::join(elems, delim); 

See also this question.

like image 199
Andre Holzner Avatar answered Sep 19 '22 22:09

Andre Holzner