26. Joining strings together separated by a delimiter

Two overloads called join_strings() are listed in the following code. One takes a container of strings and a pointer to a sequence of characters representing a separator, while the other takes two random access iterators, representing the first and one past the last element of a range, and a separator. They both return a new string created by concatenating all the input strings, using an output string stream and the std::copy function. This general-purpose function copies all the elements in the specified range to an output range, represented by an output iterator. We are using here an std::ostream_iterator that uses operator<< to write the assigned value to the specified output stream each time the iterator is assigned a value:

template <typename Iter>
std::string join_strings(Iter begin, Iter end,
char const * const separator)
{
std::ostringstream os;
std::copy(begin, end-1,
std::ostream_iterator<std::string>(os, separator));
os << *(end-1);
return os.str();
}

template <typename C>
std::string join_strings(C const & c, char const * const separator)
{
if (c.size() == 0) return std::string{};
return join_strings(std::begin(c), std::end(c), separator);
}

int main()
{
using namespace std::string_literals;
std::vector<std::string> v1{ "this","is","an","example" };
std::vector<std::string> v2{ "example" };
std::vector<std::string> v3{ };

assert(join_strings(v1, " ") == "this is an example"s);
assert(join_strings(v2, " ") == "example"s);
assert(join_strings(v3, " ") == ""s);
}
As a further exercise, you should modify the overload that takes iterators as arguments so that it works with other types of iterators, such as bidirectional iterators, thereby enabling the use of this function with lists or other containers.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset