在c ++中使用单词作为分隔符来分割字符串

时间:2013-02-06 00:48:50

标签: c++ string

我有一个非常长的字符串!并且它有词语' post'介于两者之间,我希望使用' post'来标记字符串。作为分隔符!我遇到了使用split_regex或类似的东西来进行升级库!如果有人知道一个非常有效的方法,请让我知道

-Thanks

2 个答案:

答案 0 :(得分:1)

您可以查看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;
}

答案 1 :(得分:0)

ppl这应该工作!复杂性将是“post”的数量 - 在这种情况下是分隔符,在字符串中。让我知道如果你的人有更好的运行时间,那么

#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");
}
相关问题