18

I am looking for the similar function in C++ to string.split(delimiter). It returns an array of strings cut by a specified delimiter.

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

2

1 Answer 1

5

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("%s\n",arr[i].c_str());
    return 0;
}
1
  • 1
    I deleted it, because I did not notice NO STROK (which probably has to be strtok) in title :D
    – user704565
    Commented Apr 29, 2013 at 19:24