Split a delimited string into multiple strings. - C++ STL

C++ examples for STL:string

Description

Split a delimited string into multiple strings.

Demo Code

#include <string>
#include <vector>
#include <functional>
#include <iostream>

using namespace std;

void split(const string& s, char c, vector<string>& v) {
   string::size_type i = 0;//w  ww  .  j  av  a2  s . c  om
   string::size_type j = s.find(c);

   while (j != string::npos) {
      v.push_back(s.substr(i, j-i));
      i = ++j;
      j = s.find(c, j);

      if (j == string::npos)
         v.push_back(s.substr(i, s.length()));
   }
}

int main() {
   vector<string> v;
   string s = "Account Name|Address 1|Address 2|City";

   split(s, '|', v);

   for (int i = 0; i < v.size(); ++i) {
      cout << v[i] << '\n';
   }
}

Result

Create function template that accepts any kind of character and split

template<typename T>
void split(const basic_string<T>& s, T c, vector<basic_string<T> >& v) {
   basic_string<T>::size_type i = 0;
   basic_string<T>::size_type j = s.find(c);

   while (j != basic_string<T>::npos) {
      v.push_back(s.substr(i, j-i));
      i = ++j;
      j = s.find(c, j);

      if (j == basic_string<T>::npos)
         v.push_back(s.substr(i, s.length()));
   }
 }

Related Tutorials