Split a String On A Word By Words I'm working on a text based rpg game and a couple of commands make use of a target and container pattern. So I wrote this function to split the string up on a given word and put it back together. I'm not sure how efficient it will be in the real world, but I think that it can be improved.

An example of such input and output would be:

splitOnWord("turkey leg from table", "from") -&gt; {"turkey leg", "table"}




typedef std::vector&lt;std::string&gt; StringVector;

StringVector splitOnWord(std::string line, std::string word){
    std::stringstream sstr(line);
    StringVector tmp;
    std::string str;
    int rescnt = 0;

    sstr &gt;&gt; str;
    tmp.push_back(str);
    while(sstr &gt;&gt; str) {
        if(str == word) {
            ++rescnt;
            tmp.push_back(std::string());
        } else {
            tmp[rescnt] += ' ';
            tmp[rescnt] += str;
        }
    }
    return tmp;
}
I'm not overly fond of the tmp.push_back(std::string());.

I'd rather some of the names were clearer and more readable--for example, I'm not entirely sure what rescnt is supposed to mean.

Under the circumstances, I'd tend to wonder whether we're getting enough good out of the stringstream to justify its existence either. They can be handy, but here we don't seem to be putting the capabilities to a whole lot of use.

std::vector&lt;std::string&gt; split(std::string const &amp;in, std::string const &amp;word) {
    std::vector&lt;std::string&gt; ret;

    int begin = 0;
    int end = 0;

    while (std::string::npos != (end = in.find(word, begin))) {
        ret.push_back(in.substr(begin, end-begin));
        begin = end + word.length()+1;
        while (::isspace(in[begin]))
          ++begin;
    }
    ret.push_back(in.substr(begin));
    return ret;
}