fork(21) download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4.  
  5. void dump(std::ostream &out, const std::vector<std::string> &v)
  6. {
  7. for(size_t i = 0; i < v.size(); ++i) {
  8. out << '\'' << v[ i ] << '\'' << ' ';
  9. }
  10.  
  11. out << std::endl;
  12. }
  13.  
  14. size_t split(const std::string &txt, std::vector<std::string> &strs, char ch)
  15. {
  16. size_t pos = txt.find( ch );
  17. size_t initialPos = 0;
  18. strs.clear();
  19.  
  20. // Decompose statement
  21. while( pos != std::string::npos ) {
  22. strs.push_back( txt.substr( initialPos, pos - initialPos ) );
  23. initialPos = pos + 1;
  24.  
  25. pos = txt.find( ch, initialPos );
  26. }
  27.  
  28. // Add the last one
  29. strs.push_back( txt.substr( initialPos, std::min( pos, txt.size() ) - initialPos + 1 ) );
  30.  
  31. return strs.size();
  32. }
  33.  
  34. int main()
  35. {
  36. std::vector<std::string> v;
  37.  
  38. split( "This is a test", v, ' ' );
  39. dump( std::cout, v );
  40.  
  41. split( "1,2,3, 4, 5, 6, 7,8,9", v, ',' );
  42. dump( std::cout, v );
  43.  
  44. return 0;
  45. }
  46.  
Success #stdin #stdout 0s 4416KB
stdin
Standard input is empty
stdout
'This' '' 'is' 'a' '' 'test' 
'1' '2' '3' ' 4' ' 5' ' 6' ' 7' '8' '9'