All I've found is boost::algorithm::string::join
. However, it seems like overkill to use Boost only for join. So maybe there are some time-tested recipes?
UPDATE:
Sorry, the question caption were bad.
I'm looking for method to concatenate strings with separator, not just to concatenate one-by-one.
Python String join() Methodjoin() is an inbuilt string function in Python used to join elements of the sequence separated by a string separator. This function joins elements of a sequence and makes it a string.
The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator.
Sets can be joined in Python in a number of different ways. For instance, update() adds all the elements of one set to the other. Similarly, union() combines all the elements of the two sets and returns them in a new set. Both union() and update() operations exclude duplicate elements.
join() to combine a list of objects into a string. Use list comprehension by using str(object) on each object to return a list of strings. Then use the str. join() method to combine the list of strings into a single string.
Since you're looking for a recipe, go ahead and use the one from Boost. Once you get past all the genericity, it's not too complicated:
Here's a version that works on two iterators (as opposed to the Boost version, which operates on a range.
template <typename Iter>
std::string join(Iter begin, Iter end, std::string const& separator)
{
std::ostringstream result;
if (begin != end)
result << *begin++;
while (begin != end)
result << separator << *begin++;
return result.str();
}
If you really want ''.join()
, you can use std::copy
with an std::ostream_iterator
to a std::stringstream
.
#include <algorithm> // for std::copy
#include <iterator> // for std::ostream_iterator
std::vector<int> values(); // initialize these
std::stringstream buffer;
std::copy(values.begin(), values.end(), std::ostream_iterator<int>(buffer));
This will insert all the values to buffer
. You can also specify a custom separator for std::ostream_iterator
but this will get appended at the end (this is the significant difference to join
). If you don't want a separator, this will do just what you want.
simply, where the type in the container is an int:
std::string s = std::accumulate(++v.begin(), v.end(), std::to_string(v[0]),
[](const std::string& a, int b){
return a + ", " + std::to_string(b);
});
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