Advertisement
fimas

String split function

Jan 14th, 2015
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.78 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. vector<string> split(string subject, string delimiter)
  8. {
  9.     vector<string> out;
  10.     string tmp;
  11.  
  12.     size_t start = 0;
  13.     size_t end = subject.find(delimiter, start);
  14.  
  15.     tmp = subject.substr(start, end);
  16.  
  17.     out.push_back(tmp);
  18.  
  19.     if (end == string::npos)
  20.     {
  21.         return out;
  22.     }
  23.  
  24.     do
  25.     {
  26.         start = end + delimiter.length();
  27.         end = subject.find(delimiter, start);
  28.  
  29.         tmp = subject.substr(start, end);
  30.  
  31.         out.push_back(tmp);
  32.  
  33.         if (end == string::npos)
  34.         {
  35.             break;
  36.         }
  37.        
  38.     } while (tmp.length() > 0);
  39.  
  40.     return out;
  41. }
  42.  
  43. int _tmain(int argc, _TCHAR* argv[])
  44. {
  45.     vector<string> subs = split("1,2,3,4", ",");
  46.  
  47.     for (auto sub : subs)
  48.     {
  49.         cout << sub << endl;
  50.     }
  51.  
  52.     cin.get();
  53.  
  54.     return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement