bana
bana

Reputation: 397

splitting a string using words as delimieters in c++

I have a string like really really long ! and it has word 'post' in between and I want to tokenize the string using 'post' as the delimiter ! i came across the boost library to do so with split_regex or something like that ! if any one knows of a really efficient method please do let me know

-thanks

Upvotes: 1

Views: 273

Answers (2)

bana
bana

Reputation: 397

ppl this should work ! complexity would be number of "post" - delimiter in this case, in the string . let me know if you people have better run time then this

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;

void split(const string& str, const string& delimiter = "post") {
    vector <string> tokens;

    string::size_type lastPos = 0;
    string::size_type pos = str.find(delimiter, lastPos);

    while (string::npos != pos) {
        // Found a token, add it to the vector.
        cout << str.substr(lastPos, pos - lastPos) << endl;
        //tokens.push_back(str.substr(lastPos+4, pos - lastPos));
        lastPos = pos + delimiter.size();
        pos = str.find(delimiter, lastPos);
    }


}

int main() {
   split("wat post but post get post roast post");
}

Upvotes: 0

StarPinkER
StarPinkER

Reputation: 14281

You can take a look at a Boost String Algorithms Library

#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <boost/algorithm/string/iter_find.hpp>
#include <boost/algorithm/string/finder.hpp>
int main()
{
    std::string input = "msg1foomsg2foomsg3";

    std::vector<std::string> v;
    iter_split(v, input, boost::algorithm::first_finder("foo"));

    copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, " "));
    std::cout << std:endl;
}

Upvotes: 1

Related Questions