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

1 Answer

0 votes
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm> // find

std::string move_word_to_end(const std::string& s, const std::string& word) {
    std::istringstream iss(s);
    std::vector<std::string> parts;
    std::string token;

    // Split into words
    while (iss >> token) {
        parts.push_back(token);
    }

    // Find and move the word
    auto it = std::find(parts.begin(), parts.end(), word);
    if (it != parts.end()) {
        parts.erase(it);
        parts.push_back(word);
    }

    // Rebuild the string
    std::ostringstream oss;
    for (size_t i = 0; i < parts.size(); ++i) {
        if (i > 0) oss << ' ';
        oss << parts[i];
    }

    return oss.str();
}

int main() {
    std::string s = "Would you like to know more? (Explore and learn)";
    std::string word = "like";

    std::string result = move_word_to_end(s, word);
    std::cout << result << "\n";
}


/*
run:

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

*/

 



answered Feb 3 by avibootz
...