128

I recently wanted to use boost::algorithm::join but I couldn't find any usage examples and I didn't want to invest a lot of time learning the Boost Range library just to use this one function.

Can anyone provide a good example of how to use join on a container of strings? Thanks.

Dan Hook
  • 6,769
  • 7
  • 35
  • 52
  • 32
    When looking for examples for boost library "foo", it is often a good idea to look at boost/libs/foo/examples and boost/libs/foo/test. In the present case, you could look at boost/libs/algorithm/string/test/join_test.cpp – Éric Malenfant Dec 02 '09 at 15:15

2 Answers2

245
#include <boost/algorithm/string/join.hpp>
#include <vector>
#include <iostream>

int main()
{
    std::vector<std::string> list;
    list.push_back("Hello");
    list.push_back("World!");

    std::string joined = boost::algorithm::join(list, ", ");
    std::cout << joined << std::endl;
}

Output:

Hello, World!
Rakete1111
  • 47,013
  • 16
  • 123
  • 162
Tristram Gräbener
  • 9,601
  • 3
  • 34
  • 50
  • 4
    Can it support custom types? For example, class `A` has a method `ToString` which returns a `string` value.Can I use `join` to join a `vector` by calling `ToString` on each element? – Ken Zhang Feb 08 '18 at 02:56
  • @KenZhang: No, because this is a rather specialized implementation. The usual STL style is to use iterator pairs, and then you can use `boost::transform_iterator` to wrap the `.ToString` methods. But this `join` method takes a container instead of an iterator pair. – MSalters Sep 10 '21 at 12:51
43
std::vector<std::string> MyStrings;
MyStrings.push_back("Hello");
MyStrings.push_back("World");
std::string result = boost::algorithm::join(MyStrings, ",");

std::cout << result; // prints "Hello,World"
KeatsPeeks
  • 19,126
  • 5
  • 52
  • 83
  • 13
    This answer shows less effort than the older one and provides no added value. Why is it still present here? – arekolek Aug 05 '16 at 14:46