字符串分割-C++


void StrSplit(std::vector &vecs, const std::string &str, const char *cset) {
    std::size_t sp = 0, np = 0;

    //过滤掉前面的分割字符
    while(sp < str.size() && strchr(cset, str[sp])) ++sp;
    np = str.find_first_of(cset, sp);
    while (np != std::string::npos) {
        std::size_t len = np - sp;
        vecs.push_back(str.substr(sp, len));

        sp = np;
        while(sp < str.size() && strchr(cset, str[sp])) ++sp;
        np = str.find_first_of(cset, sp);
    }

    if (sp < str.size()) 
        vecs.push_back(str.substr(sp));
}

...

使用
std::string str("\t abc efg\thaha\r\n");
std::vector vecs;
StrSplit(vecs, str, "\t\r\n ");
for (auto x: vecs)
  std::cout << x << std::endl;

//abc
//efg
//haha

你可能感兴趣的:(字符串分割-C++)