Friday, May 17, 2013

string parser c++

Splitting a string to a vector of words is very common task in text processing field. And I try to write  several lines of C++ code to deal this problem.


size_t split(const std::string &line, std::vector<std::string> &wordVec, const char sep)
{
    wordVec.clear();
    std::string::size_type pos = 0, prev_pos = 0;
    while (std::string::npos != (pos = line.find_first_of(' ', pos))) {
        wordVec.push_back(line.substr(prev_pos, pos - prev_pos));
        prev_pos = ++pos;
    }
    if(prev_pos < line.size())
    {
        wordVec.push_back(line.substr(prev_pos, pos-prev_pos));
//        std::cout<<"["<
    }
    
    return wordVec.size();
}



No comments: