Tip of the Week #36: New Join API

Originally published as totw/36 on 2013-03-21

By Greg Miller ([email protected])

Updated 2018-01-24

“I got a good mind to join a club and beat you over the head with it.” – Groucho Marx

Many of you asked for a new joining API and we heard you. We now have one joining function to replace them all, and it is spelled absl::StrJoin(). You simply give it a collection of objects to be joined and a separator string, and it does the rest. It will work with collections of std::string, absl::string_view, int, double – any type that absl::StrCat() supports. If you need to join a type that will not StrCat(), you can also provide a custom Formatter for that type; we’ll see below how the use of a Formatter will let us nicely join a map.

Now for some quick examples:

std::vector<std::string> v = {"a", "b", "c"};
std::string s = absl::StrJoin(v, "-");
// s == "a-b-c"

std::vector<absl::string_view> v = {"a", "b", "c"};
std::string s = absl::StrJoin(v.begin(), v.end(), "-");
// s == "a-b-c"

std::vector<int> v = {1, 2, 3};
std::string s = absl::StrJoin(v, "-");
// s == "1-2-3"

const int a[] = {1, 2, 3};
std::string s = absl::StrJoin(a, "-");
// s == "1-2-3"

The following example passes a Formatter argument to format the pairs in a map, using a different separator. This makes the output nice and readable.

std::map<std::string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}};
std::string s = absl::StrJoin(m, ";", absl::PairFormatter("="));
// s == "a=1;b=2;c=3"

You can also pass a C++ lambda expression as a Formatter.

std::vector<Foo> foos = GetFoos();

std::string s = absl::StrJoin(foos, ", ", [](std::string* out, const Foo& foo) {
  absl::StrAppend(out, foo.ToString());
});

Please refer to absl/strings/str_join.h for more details.


Subscribe to the Abseil Blog