How to split string into words in C++

1 Answer

0 votes
#include <iostream>
#include <sstream>
#include <vector>
#include <iterator>

template <typename Out>
void split(const std::string &s, char delimiter, Out v) {
    std::istringstream iss(s);
    std::string word;
    
    while (std::getline(iss, word, delimiter)) {
        *v++ = word;
    }
}

std::vector<std::string> split(const std::string &s, char delimiter) {
    std::vector<std::string> v;
    split(s, delimiter, std::back_inserter(v));
    
    return v;
}
   
 
int main()
{
    std::string str = "C++:is:a:general:purpose:programming:language";
    
    std::vector<std::string> v = split(str, ':');
     
    for (const auto &str : v) 
        std::cout << str << "\n";        
     
    return 0;
}
 
 
 
 
 
/*
run:
         
C++
is
a
general
purpose
programming
language
    
*/

 



answered Dec 25, 2021 by avibootz
edited Dec 25, 2021 by avibootz

Related questions

1 answer 132 views
1 answer 141 views
3 answers 231 views
3 answers 224 views
224 views asked Feb 4, 2017 by avibootz
1 answer 139 views
1 answer 155 views
155 views asked Dec 25, 2021 by avibootz
...