Heh heh heh, I wrote an awesomeness.
Funny how old topics stick with you. Someone asked about tokenizing strings with a function that returns an array over at SO. This was my answer.
https://stackoverflow.com/a/69512860/2706707
Feeling kind of accomplished, I guess.
That's one of the reasons I moved from c to C++ about 25 years ago - to get away from code like this. Split is dead easy in C++20:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <vector>
#include <iostream>
#include <string>
#include <ranges>
auto str_split(const std::string& str, const std::string& delim) {
std::vector<std::string> vec;
for (const auto& e : std::ranges::split_view(str, delim))
if (const auto d {std::ranges::distance(e)}; d > 0)
vec.emplace_back(&*e.begin(), &*e.begin() + d);
return vec;
}
int main() {
const auto split {str_split("++All+Along+the+Watchtower++", "+")};
for (const auto& s : split)
std::cout << s << '\n';
std::cout << '\n';
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> split( const string &str, string delim )
{
vector<string> result;
for ( int p = 0, q = 0; q != string::npos; p = q + 1 )
{
q = str.find_first_of( delim, p );
result.push_back( str.substr( p, ( q == string::npos ? str.size() : q ) - p ) );
}
return result;
}
int main()
{
for ( string s : split( "Someone+left+the+cake+out+in+the+rain", "+" ) ) cout << s << '\n';
}
|
Someone
left
the
cake
out
in
the
rain |
Topic archived. No new replies allowed.