Home > Software design >  The c 20 way to parse a simple delimited string
The c 20 way to parse a simple delimited string

Time:04-12

There are plenty of questions and answers here on how to parse delimited strings. I am looking for c 20 ish answers. The following works, but it feels lacking. Any suggestions to do this more elegantly?

const std::string& n = "1,2,3,4";
const std::string& delim = ",";
std::vector<std::string> line;
for (const auto& word : std::views::split(n, delim)) {
    line.push_back(std::string(word.begin(), word.end()));
    }

CodePudding user response:

There is no need to create substrings of type std::string, you can use std::string_view to avoid unnecessary memory allocation. With the introduction of C 23 ranges::to, this can be written as

const std::string& n = "1,2,3,4";
const std::string& delim = ",";
const auto line = n | std::views::split(delim)
                    | std::ranges::to<std::vector<std::string_view>>();

Demo

  • Related