https://www.cnblogs.com/stonebloom-yu/p/6542756.html
#include <cstring> #include <cstdio> #include <iostream> #include <vector> using namespace std; vector<string> split(const string &str,const string &pattern){ //本函数功能:将字符串str按pattern分割,返回string容器 //const char* convert to char* //标准库的string类提供了3个成员函数来从一个string得到c类型的字符数组:c_str()、data()、copy(p,n) //c_str():生成一个const char*指针,指向以空字符终止的数组 char * strc = new char[strlen(str.c_str())+1]; strcpy(strc, str.c_str()); vector<string> resultVec; char* tmpStr = strtok(strc, pattern.c_str()); while (tmpStr != NULL) { resultVec.push_back(string(tmpStr)); tmpStr = strtok(NULL, pattern.c_str()); } delete[] strc; return resultVec; } int main(){ string str = "/a/b/c/d/e/y/"; string sep = "/"; vector<string> rt = split(str, sep); int len = rt.size(); for(int i = 0; i < len; i++){ cout << rt[i] << endl; } return 0; }