split 函数用 string find 函数实现的
split1 用 strtok 函数实现的
split2 使用 stringstream 和 getline实现

void split(const string &s, vector<string> &tokens, const string &delimiters = " ") {
    string::size_type lastPos = s.find_first_not_of(delimiters, 0);
    string::size_type pos = s.find_first_of(delimiters, lastPos);
    while (string::npos != pos || string::npos != lastPos) {
        tokens.push_back(s.substr(lastPos, pos - lastPos));
        lastPos = s.find_first_not_of(delimiters, pos);
        pos = s.find_first_of(delimiters, lastPos);
    }
}

vector<string> split1(string str, const string& delim) {
    vector<string> ans;
    char* pos = strtok((char*)str.c_str(), delim.c_str());
    while (pos != NULL) {
        ans.push_back(pos);
        pos = strtok(NULL, delim.c_str());
    }
    return ans;
}

vector<string> split2(string str, const char c) {
    vector<string> ans;
    stringstream sIn(str);
    string s;
    while (getline(sIn, s, c)) {
        ans.push_back(s);
    }
    return ans;
}

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐