Splitting a string into a vector using C++
Posted by Samath
Last Updated: January 04, 2017

My aim in this program is split up a string using a delimiter and add each sperated element to the a vector then iterate over the vector and output the values. The code is provided below.


#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;

vector<string> split(string str, char delimiter) {
  vector<string> result;
  stringstream ss(str); // Turn the string into a stream.
  string tok;
  while(getline(ss, tok, delimiter)) {
  return result;

int main(int argc, char **argv) {
  string mystring = "apple,banana,mango,orange";
  vector<string> sep = split(mystring, ',');
  for(int i = 0; i < sep.size(); ++i)
    cout << sep[i] << endl;


Related Content
VECTOR of counters in C++
VECTOR of counters in C++
Samath | Jan 06, 2021