fork(14) download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. std::vector<std::string> split_string(const std::string& str,
  6. const std::string& delimiter)
  7. {
  8. std::vector<std::string> strings;
  9.  
  10. std::string::size_type pos = 0;
  11. std::string::size_type prev = 0;
  12. while ((pos = str.find(delimiter, prev)) != std::string::npos)
  13. {
  14. strings.push_back(str.substr(prev, pos - prev));
  15. prev = pos + 1;
  16. }
  17.  
  18. // To get the last substring (or only, if delimiter is not found)
  19. strings.push_back(str.substr(prev));
  20.  
  21. return strings;
  22. }
  23.  
  24. int main()
  25. {
  26. auto strings = split_string("foo\nbar\nthis\nworks", "\n");
  27. int i = 1;
  28. for (auto itr = strings.begin(); itr != strings.end(); itr++)
  29. std::cout << "#" << i++ << " - \"" << *itr << "\"\n";
  30. }
  31.  
Success #stdin #stdout 0s 3020KB
stdin
Standard input is empty
stdout
#1 - "foo"
#2 - "bar"
#3 - "this"
#4 - "works"