How to move the first word to the end of a string in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <ranges> // istream_iterator
#include <algorithm> // rotate

std::string move_first_word_to_end_of_string(const std::string& s) {
    std::istringstream iss(s);
    std::vector<std::string> words(std::istream_iterator<std::string>{iss},
                                   std::istream_iterator<std::string>{});

    if (words.size() <= 1)
        return s;

    std::rotate(words.begin(), words.begin() + 1, words.end());

    std::ostringstream oss;
    for (size_t i = 0; i < words.size(); ++i) {
        if (i) oss << ' ';
        oss << words[i];
    }
    
    return oss.str();
}

int main() {
    std::string s = "Would you like to know more? (Explore and learn)";
    std::cout << move_first_word_to_end_of_string(s) << "\n";
}



/*
run:

you like to know more? (Explore and learn) Would

*/

 



answered Feb 5 by avibootz
...