How to convert a string to a vector of words in C++

1 Answer

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

std::vector<std::string> ConvertStringToVectorOfWords(std::string str) {
    std::vector<std::string> words;
    std::stringstream ss(str);
    std::string word;

    while (ss >> word) {
        words.push_back(word);
    }   
    
    return words;
}

int main() {
    std::string str = "C++ C Java Python PHP Rust";
    std::stringstream ss(str);

    std::vector<std::string> words = ConvertStringToVectorOfWords(str);

    for (const auto& w : words) {
        std::cout << w << std::endl;
    }
}

  
 
/*
run1:
 
C++
C
Java
Python
PHP
Rust

*/

 



answered Nov 23, 2024 by avibootz
edited Nov 23, 2024 by avibootz
...