字符串分隔

I use this to split string by a delim.

The first puts the results in a pre-constructed vector,

the second returns a new vector.

#include <string>
#include <sstream>
#include <vector>

using namespace std;

vector<string> &split(const string &s, char delim, vector<string> &elems) {
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}


vector<string> split(const string &s, char delim) {
    vector<string> elems;
    split(s, delim, elems);
    return elems;
}

Note that this solution does not skip empty tokens, so the following will find 4 items, one of which is empty:

vector<string> x = split("one:two::three", ':');

参见:

       from

posted @ 2016-06-21 20:50  fndefbwefsowpvqfx  阅读(147)  评论(0编辑  收藏  举报