类似于C++中java的string.split("")的函数

15 c++ string split

我正在寻找C++中的类似函数.string.split(delimiter)它确实返回由指定分隔符剪切的字符串数组..

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)

有一个好的答案,但作者删除了它.

__PRE__

小智 5

您可以使用 strtok。 http://www.cplusplus.com/reference/cstring/strtok/

#include <string>
#include <vector>
#include <string.h>
#include <stdio.h>
std::vector<std::string> split(std::string str,std::string sep){
    char* cstr=const_cast<char*>(str.c_str());
    char* current;
    std::vector<std::string> arr;
    current=strtok(cstr,sep.c_str());
    while(current!=NULL){
        arr.push_back(current);
        current=strtok(NULL,sep.c_str());
    }
    return arr;
}
int main(){
    std::vector<std::string> arr;
    arr=split("This--is--split","--");
    for(size_t i=0;i<arr.size();i++)
        printf("%s\n",arr[i].c_str());
    return 0;
}
Run Code Online (Sandbox Code Playgroud)