Tokenizing/splitting string in c++

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 <iostream>
#include <string>
#include <string.h>
 
#include <memory>
#include <stdlib.h>
#include <stdio.h>
#include <list>
#include <vector>
 
using namespace std;
 
void split(vector<string>& 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<string> o1;
  split(o1, str, ",");
 
  for (int i = 0; i < o1.size(); ++i)
  {
     cout << "token = " << o1[i] <<endl;
  }
 
  return 0;
}

Results

Supplied string : apple,organge,cherry
Delemeter : “,”
Output

  • apple
  • organge
  • cherry

Leave a Comment

Your email address will not be published. Required fields are marked *