This method uses strtok to tokeninze our string given a specific delimeter, results of that are put into supplied vector. There are few other ways we can do this but this one is straight forward.
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
void split(vector& out, const string& in, const string& delim)
{
char* lc = (char*) malloc(in.size());
strcpy(lc, in.c_str());
strtok(lc, delim.c_str());
while (lc)
{
string s = lc;
out.push_back(s);
lc = strtok(NULL, delim.c_str());
}
free(lc);
}
int main(int argc, char* args[])
{
string str = "apple,organge,cherry";
vector o1;
split(o1, str, ",");
for (int i = 0; i < o1.size(); ++i)
{
cout << "token = " << o1[i] <
Results
Supplied string : apple,organge,cherry
Delemeter : ","
Output
- apple
- organge
- cherry
Leave a Reply