0

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;
}
gust
  • 878
  • 9
  • 23
  • 3
    That doesn't make sense. A `string_view` is contiguous. Outside of *very* specific circumstances, two unrelated `string_view`s are not. The only way to create a contiguous range of characters from non-contiguous ranges... is to allocate a contiguous range. Like in a `std::string`. – Nicol Bolas Jul 14 '22 at 21:48

1 Answers1

2

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.

Thom A
  • 88,727
  • 11
  • 45
  • 75
sorosh_sabz
  • 2,356
  • 2
  • 32
  • 53