How to split a string of words into 3-word lines of text in C++

1 Answer

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

std::vector<std::string> split_string_into_3_word_lines(std::string str) {
    std::vector<std::string> words;
    std::stringstream ss(str);
    std::string word;
    
    while (ss >> word) {
        words.push_back(word);
    }

    std::vector<std::string> threeWordLines;
    
    int length = words.size();
    for (int i = 0; i < length; i += 3) {
        std::string oneline = "";
        for (int j = i; j < std::min(i + 3, length); j++) {
            oneline += words[j] + " ";
        }
        threeWordLines.push_back(oneline.substr(0, oneline.length() - 1));
    }

    return threeWordLines;
}

int main() {
    std::string str = "java c c++ python rust go php typescript";

    std::vector<std::string> threeWordLines = split_string_into_3_word_lines(str);

    for (std::string line : threeWordLines) {
        std::cout << line << std::endl;
    }
}

 
 
   
/*
run:

java c c++
python rust go
php typescript
  
*/

 



answered May 11, 2024 by avibootz

Related questions

...