fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <utility>
  5. #include <iterator>
  6.  
  7. template < typename OUTPUT_ITERATOR >
  8. OUTPUT_ITERATOR split( const std::string& str, const std::string& delimiters,
  9. OUTPUT_ITERATOR dest )
  10. {
  11. std::string::size_type pos = str.find_first_of(delimiters) ;
  12. std::string::size_type start = 0 ;
  13.  
  14. while( pos != std::string::npos )
  15. {
  16. std::string token = str.substr( start, pos-start ) ;
  17. if( !token.empty() ) *dest++ = token ;
  18. start = pos+1 ;
  19. pos = str.find_first_of( delimiters, start ) ;
  20. }
  21.  
  22. if( start < str.size() ) *dest++ = str.substr(start) ;
  23.  
  24. return dest ;
  25. }
  26.  
  27. std::vector<std::string> split( const std::string& str, const std::string& delimiters )
  28. {
  29. std::vector<std::string> result ;
  30. split( str, delimiters, std::back_inserter(result) ) ;
  31. return result ;
  32. }
  33.  
  34. int main()
  35. {
  36. const std::string jabber = "`Twas brillig, and the slithy toves\n"
  37. "Did gyre and gimble in the wabe:\n"
  38. "All mimsy were the borogoves,\n"
  39. "And the mome raths outgrabe.\n" ;
  40. const std::string delimiters = "\n ,:.!" ;
  41.  
  42. int n = 0 ;
  43. for( const std::string& token : split( jabber, delimiters ) )
  44. std::cout << ++n << ". " << token << '\n' ;
  45. std::cout << '\n' ;
  46.  
  47. split( jabber, delimiters, std::ostream_iterator<std::string>( std::cout, " | " ) ) ;
  48. std::cout << "\n\n" ;
  49.  
  50. const char cstr[] = "Beware the Jabberwock, my son!\n"
  51. "The jaws that bite, the claws that catch!\n"
  52. "Beware the Jubjub bird, and shun\n"
  53. "The frumious Bandersnatch!\n" ;
  54.  
  55. split( cstr, delimiters, std::ostream_iterator<std::string>( std::cout, " | " ) ) ;
  56. std::cout << '\n' ;
  57.  
  58. }
  59.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
1. `Twas
2. brillig
3. and
4. the
5. slithy
6. toves
7. Did
8. gyre
9. and
10. gimble
11. in
12. the
13. wabe
14. All
15. mimsy
16. were
17. the
18. borogoves
19. And
20. the
21. mome
22. raths
23. outgrabe

`Twas | brillig | and | the | slithy | toves | Did | gyre | and | gimble | in | the | wabe | All | mimsy | were | the | borogoves | And | the | mome | raths | outgrabe | 

Beware | the | Jabberwock | my | son | The | jaws | that | bite | the | claws | that | catch | Beware | the | Jubjub | bird | and | shun | The | frumious | Bandersnatch |