Advertisement
obernardovieira

Split String [3 different ways]

Mar 5th, 2014
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1. //none made ​​by me
  2.  
  3. #include <cstring>
  4. #include <iostream>
  5. #include <vector>
  6. #include <string>
  7. #include <sstream>
  8. #include <iterator>
  9.  
  10. int main()
  11. {
  12.    
  13.     //1
  14.     char input[100] = "A bird came down the walk";
  15.     char *token = std::strtok(input, " ");
  16.     while (token != NULL) {
  17.         std::cout << token << '\n';
  18.         token = std::strtok(NULL, " ");
  19.     }
  20.    
  21.     //2
  22.    
  23.     std::string str = "This is a string";
  24.     std::istringstream buf(str);
  25.     std::istream_iterator<std::string> beg(buf), end;
  26.  
  27.     std::vector<std::string> tokens(beg, end); // done!
  28.  
  29.     for(auto& s: tokens)
  30.         std::cout << '"' << s << '"' << '\n';
  31.        
  32.     //3
  33.        
  34.     std::string s = "scott>=tiger>=mushroom";
  35.     std::string delimiter = ">=";
  36.    
  37.     size_t pos = 0;
  38.     std::string ttoken;
  39.     while ((pos = s.find(delimiter)) != std::string::npos) {
  40.         ttoken = s.substr(0, pos);
  41.         std::cout << ttoken << std::endl;
  42.         s.erase(0, pos + delimiter.length());
  43.     }
  44.     std::cout << s << std::endl;
  45.    
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement