其他分享
首页 > 其他分享> > std::string 字符串分割

std::string 字符串分割

作者:互联网

#include <iostream>
#include <string>
#include <vector>

std::vector<std::string> vStringSplit(const  std::string& s, const std::string& delim=",")
{
    std::vector<std::string> elems;
    size_t pos = 0;
    size_t len = s.length();
    size_t delim_len = delim.length();
    if (delim_len == 0) return elems;
    while (pos < len)
    {
        int find_pos = s.find(delim, pos);
        if (find_pos < 0)
        {
            elems.push_back(s.substr(pos, len - pos));
            break;
        }
        elems.push_back(s.substr(pos, find_pos - pos));
        pos = find_pos + delim_len;
    }
    return elems;
}
void test() {
    auto res=vStringSplit("a,b,c");
    for(int i=0;i<res.size();i++) {
        std::cout<<res[i]<<std::endl;
    }
}

标签:std,string,delim,pos,len,elems,字符串,find
来源: https://www.cnblogs.com/smallredness/p/11178063.html