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 103 views
103 views asked Aug 20, 2023 by avibootz
1 answer 235 views
1 answer 158 views
1 answer 146 views
1 answer 144 views
3 answers 240 views
1 answer 145 views
...