c++11 分割字符串 split string

创建日期: 2023-05-26 17:54 | 作者: 风波 | 浏览次数: 16 | 分类: C++

使用指定的字符串 split string

#include <vector>
#include <iostream>

std::vector<std::string> split(const std::string& s, const std::string delimiter=" ") {
    std::string cp = s;
    std::vector<std::string> vecStr;

    size_t pos = 0;
    std::string token;
    while ((pos = cp.find(delimiter)) != std::string::npos) {
        token = cp.substr(0, pos);
        vecStr.push_back(token);
        cp.erase(0, pos + delimiter.length());
    }
    vecStr.push_back(cp);
    return vecStr;
}

int main() {
    std::string s = "Hello World!:ok~cdd-ass-jjd~~";
    auto v1 = split(s);
    for (auto x : v1) {
        std::cout << "[" << x << "], ";
    }
    std::cout << std::endl;
    return 0;
}

参考:https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c

16 浏览
15 爬虫
0 评论