Search code examples
c++boostc++17string-view

Join a container of `std::string_view`


How can you concisely combine a container of std::string_views?

For instance, boost::algorithm::join is great, but it only works for std::string. An ideal implementation would be

static std::string_view unwords(const std::vector<std::string_view>& svVec) {
  std::string_view joined;
  boost::algorithm::join(svVec," "); 
  return joined;
}

Solution

  • short C++20 answer version:

        using namespace std::literals;
        const auto bits = { "https:"sv, "//"sv, "cppreference"sv, "."sv, "com"sv };
        for (char const c : bits | std::views::join) std::cout << c;
        std::cout << '\n';
    

    since C++23 if you want to add special string or character between parts you can just use simple join_with and your code is just below (from official cppreference example)

    #include <iostream>
    #include <ranges>
    #include <vector>
    #include <string_view>
     
    int main() {
        using namespace std::literals;
     
        std::vector v{"This"sv, "is"sv, "a"sv, "test."sv};
        auto joined = v | std::views::join_with(' ');
     
        for (auto c : joined) std::cout << c;
        std::cout << '\n';
    }
    

    Note1: if you do not like use not stable release of language, you can simple use range-v3 library for join_with views

    Note2: As Nicol Bolas you cannot join literally to exact one string_view without any copy (you can copy to string and ... :D), if you want to know more detailed about that you can see Why can't I construct a string_view from range iterators? SO question and answer.