'The c++ 20 way to parse a simple delimited string
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()));
}
Solution 1:[1]
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>>();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
