How to split a string using ranges in C++20

1 Answer

0 votes
#include <iostream>
#include <string>
#include <string_view>
#include <ranges>
#include <vector>

/*
    split_ranges(s, delim)
    ----------------------
    Splits a string_view using C++20 ranges and returns a vector<string>.
    This uses:
      - std::views::split      → splits into subranges
      - std::views::transform  → converts each subrange into std::string

    The function is efficient because:
      - It avoids manual loops
      - It avoids repeated allocations except for final strings
      - It uses lazy range pipelines
*/
std::vector<std::string> split_ranges(std::string_view s, char delim) {
    auto rng =
        s
        | std::views::split(delim)
        | std::views::transform([](auto&& sub) {
              // Convert each subrange into a std::string
              return std::string(sub.begin(), sub.end());
          });

    // Materialize the lazy range into a vector<string>
    return {rng.begin(), rng.end()};
}

int main() {
    std::string input = "What if this is the best version?";
    char delim = ' ';

    // Use the split_ranges function
    auto parts = split_ranges(input, delim);

    std::cout << "\nSplit result:\n";
    for (const auto& p : parts) {
        std::cout << "[" << p << "]\n";
    }
}



/*
run:

Split result:
[What]
[if]
[this]
[is]
[the]
[best]
[verion?]

*/

 



answered Jul 19 by avibootz

Related questions

...