runnig

split string into words

Oct 1st, 2012
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.97 KB | None | 0 0
  1.  
  2. #include <string>
  3. #include <vector>
  4. #include <iostream>
  5. #include <assert.h>
  6.  
  7. std::vector<std::string> split(const std::string &s)
  8. {
  9.     typedef std::string::size_type pos_t;
  10.     pos_t beg_pos, end_pos;
  11.    
  12.     const std::string delims("\t ;,.");
  13.     std::vector<std::string> ret;
  14.    
  15.     beg_pos = s.find_first_not_of(delims);
  16.    
  17.     while(beg_pos != std::string::npos)
  18.     {
  19.         end_pos = s.find_first_of(delims, beg_pos);
  20.        
  21.         if(std::string::npos == end_pos)
  22.         {
  23.             end_pos = s.length();
  24.         }
  25.        
  26.         ret.push_back(s.substr(beg_pos, end_pos-beg_pos));
  27.         beg_pos = s.find_first_not_of(delims, end_pos);
  28.     }
  29.     return ret;
  30. }
  31.  
  32. int _tmain(int argc, _TCHAR* argv[])
  33. {
  34.     std::string s("\tbo1.bo2  bobo3 a");
  35.     std::vector<std::string> v = split(s);
  36.     assert(v.size() == 4);
  37.     assert(v[0] == "bo1");
  38.     assert(v[1] == "bo2");
  39.     assert(v[2] == "bobo3");
  40.     assert(v[3] == "a");
  41.     return 0;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment