Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to replace a random word in a string with a random word from a vector of words using C++

1 Answer

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

std::string replace_random_word(const std::string& text,
                                const std::vector<std::string>& replacements)
{
    // Split text into words
    std::stringstream ss(text);
    std::vector<std::string> words;
    std::string word;

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

    if (words.empty() || replacements.empty()) {
        return text; // nothing to do
    }

    // Random engine
    static std::random_device rd;
    static std::mt19937 gen(rd());

    // Pick random index in the sentence
    std::uniform_int_distribution<> dist_word(0, words.size() - 1);
    int idx = dist_word(gen);

    // Pick random replacement word
    std::uniform_int_distribution<> dist_repl(0, replacements.size() - 1);
    words[idx] = replacements[dist_repl(gen)];

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

    return out.str();
}

int main() {
    std::string text = "The quick brown fox jumps over the lazy dog";
    std::vector<std::string> replacement_words = {"c#", "c++", "java", "rust", "python"};

    std::string result = replace_random_word(text, replacement_words);
    std::cout << result << "\n";

    return 0;
}



/*
run:

The quick brown fox jumps over rust lazy dog

*/

 



answered 7 hours ago by avibootz

Related questions

...