Wednesday, April 28, 2010

Joining string collections

Problem: Join a collection of strings, with a given separator

Answer: Use stlsoft::string_concatenator()

Related Chapter: Extended STL, volume 1 chapter 40

Example:

  typedef std::string           string_t;
  typedef std::vector<string_t> strings_t;

  strings_t patterns;

  patterns.push_back("*.cpp");
  patterns.push_back("*.cxx");
  patterns.push_back("*.hpp");
  patterns.push_back("*.hxx");

  string_t result;

  std::copy(coll.begin(), coll.end()
          , stlsoft::string_concatenator(result, "|"));

  assert("*.cpp|*.cxx|*.hpp|*.hxx" == result);