Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,990 questions

51,935 answers

573 users

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 118 views
1 answer 135 views
3 answers 216 views
3 answers 209 views
209 views asked Feb 4, 2017 by avibootz
1 answer 128 views
1 answer 140 views
140 views asked Dec 25, 2021 by avibootz
...