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 the words of a string into a vector in C++

3 Answers

0 votes
#include <iostream>
#include <string>
#include <sstream>
#include <iterator>
#include <vector>
 
using std::cout;
using std::endl;
using std::string;
using std::vector;
 
int main()
{
    string s = "c c++ java php python go rust swift";
 
    std::istringstream iss(s);
    vector<string> tokens{ std::istream_iterator<string>{iss},
                           std::istream_iterator<string>{} };
 
    for (string s : tokens) {
        cout << s << endl;
    }
}


 
/*
run:
 
c
c++
java
php
python
go
rust
swift
 
*/

 



answered May 22, 2018 by avibootz
edited Mar 2, 2025 by avibootz
0 votes
#include <iostream>
#include <string>
#include <sstream>
#include <iterator>
#include <vector>
 
template <typename Out>
void split(const std::string &s, char delimiter, Out result) {
    std::istringstream iss(s);
    std::string item;
    
    while (std::getline(iss, item, delimiter)) {
        *result++ = item;
    }
}

std::vector<std::string> split(const std::string &s, char delimiter) {
    std::vector<std::string> tokens;
    split(s, delimiter, std::back_inserter(tokens));
    
    return tokens;
}
 
int main()
{
    std::string s = "c c++ java php python go rust swift";
    
    std::vector<std::string> tokens = split(s, ' ');
 
    for (std::string s : tokens) {
        std::cout << s << std::endl;
    }
}
 
 
/*
run:
 
c
c++
java
php
python
go
rust
swift
 
*/

 



answered Mar 2, 2025 by avibootz
0 votes
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>

int main() {
    std::string s = "c c++ java php python go rust swift";
    std::istringstream iss(s);
    
    std::vector<std::string> tokens;
    
    copy(std::istream_iterator<std::string>(iss),
        std::istream_iterator<std::string>(),
        std::back_inserter(tokens));
        
    for (std::string s : tokens) {
        std::cout << s << std::endl;
    }
}

 
 
/*
run:
 
c
c++
java
php
python
go
rust
swift
 
*/

 



answered Mar 2, 2025 by avibootz

Related questions

1 answer 85 views
85 views asked Aug 20, 2023 by avibootz
1 answer 189 views
1 answer 132 views
1 answer 130 views
1 answer 122 views
3 answers 187 views
1 answer 118 views
...