首页 > 代码库 > c++ split 模板实现

c++ split 模板实现

template<typename _Fty> inline
void split(const std::string& s, const std::string& delims, _Fty op)
{
    size_t start = 0;
    size_t last = s.find(delims, start);
    while (last != std::string::npos)
    {
        op(std::move(s.substr(start, last - start)));

        last = s.find(delims, (start = last + delims.size()));
    }
    if (start < s.size())
    {
        op(std::move(s.substr(start)));
    }
}

inline
void split(const std::string& s, const std::string& delims, std::vector<std::string>& values)
{
    split(s, delims, [&values](std::string&& item) { values.push_back(std::move(item)); } );
}


int main(int, char**)
{

    std::vector<std::string> values;

    split("hello#@ffdsdf#@ffgfdg#@ gdsfd @ af#", "#", values);

    return 0;
}

c++ split 模板实现