Similar function to java's string.split(" ") in C++

This question already has an answer here:

  • How do I tokenize a string in C++? 34 answers
  • The most elegant way to iterate the words of a string [closed] 74 answers

  • You can use 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("%sn",arr[i].c_str());
        return 0;
    }
    

    I think this other stack overflow questions may answer this question:

    Split a string in C++?

    In summary, there's no built-in method like with Java, but one of the users wrote this very similar method:

    https://stackoverflow.com/a/236803/1739039

    链接地址: http://www.djcxy.com/p/19578.html

    上一篇: 在C ++中创建一个字符串拆分函数

    下一篇: 在C ++中与java的string.split(“”)类似