fork(1) download
  1. #include <iostream>
  2. #include <iterator>
  3. #include <string>
  4. #include <vector>
  5.  
  6. std::vector<std::string> split(const std::string& s, const std::string& delim)
  7. {
  8. std::vector<std::string> result;
  9.  
  10. std::size_t beg = 0;
  11. std::size_t end;
  12. while ((end = s.find(delim, beg)) != std::string::npos)
  13. {
  14. result.emplace_back(s.substr(beg, end - beg));
  15. beg = end + delim.size();
  16. }
  17.  
  18. if (beg)
  19. result.emplace_back(s.substr(beg));
  20.  
  21. return result;
  22. }
  23.  
  24. template <typename container_type>
  25. void print(std::ostream& os, const container_type& container, const std::string& sep = ", ")
  26. {
  27. for (std::size_t i = 0; i < container.size() - 1; ++i)
  28. os << container[i] << sep;
  29.  
  30. if (!container.empty())
  31. os << container.back();
  32. }
  33.  
  34. int main()
  35. {
  36. std::string s = "scott>=tiger>=mushroom";
  37. std::string d = ">=";
  38.  
  39. std::cout << '"' << s << "\" split on \"" << d << "\" yields:\n";
  40. print(std::cout, split(s,d));
  41. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
"scott>=tiger>=mushroom" split on ">=" yields:
scott, tiger, mushroom