Example: String Split
Here, we'll determine whether string_view can be used for splitting a string into several view objects.
We'll cover the following...
string_view
might be a potential optimization for string splitting. If you own a large persistent string, you might want to create a list of string_view objects that maps words of that larger string.
Note: The code is inspired by the article by Marco Arena - string_view odi et amo1.
Press + to interact
#include <iostream>#include <string>#include <vector>#include<algorithm>using namespace std;std::vector<std::string_view>splitSV(std::string_view strv, std::string_view delims = " "){std::vector<std::string_view> output; auto first = strv.begin();while (first != strv.end()) {const auto second = std::find_first_of( first, std::cend(strv),std::cbegin(delims), std::cend(delims));if (first != second) {output.emplace_back(strv.substr(std::distance(strv.begin(), first), std::distance(first, second)));}if (second == strv.end())break;first = std::next(second);}return output;}int main() {const std::string str {"Hello Extra,,, Super, Amazing World"};for (const auto& word : splitSV(str, " ,"))std::cout << word << '\n';}
The algorithm iterates over the input ...