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,970 questions

51,912 answers

573 users

How to remove a random word from a string in C++

1 Answer

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

std::string removeRandomWord(const std::string& input) {
    std::istringstream iss(input);
    std::vector<std::string> words;
    std::string word;

    // Split the input string into words
    while (iss >> word) {
        words.push_back(word);
    }

    // Seed the random number generator
    std::srand(std::time(0));

    // Generate a random index
    int randomIndex = std::rand() % words.size();

    // Remove the word at the random index
    words.erase(words.begin() + randomIndex);

    // Reconstruct the string without the random word
    std::ostringstream oss;
    for (size_t i = 0; i < words.size(); i++) {
        if (i != 0) {
            oss << " ";
        }
        oss << words[i];
    }

    return oss.str();
}

int main() {
    std::string str = "I'm not clumsy The floor just hates me";
    
    std::string result = removeRandomWord(str);
    
    std::cout << "str: " << str << std::endl;
    std::cout << "result: " << result << std::endl;
}



/*
run:

str: I'm not clumsy The floor just hates me
result: I'm clumsy The floor just hates me

*/

 



answered May 4, 2025 by avibootz

Related questions

2 answers 187 views
1 answer 68 views
1 answer 100 views
1 answer 82 views
1 answer 95 views
2 answers 103 views
...