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

51,766 answers

573 users

How to remove the middle word from a string in C++

1 Answer

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

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

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

    if (words.size() <= 2)
        return input;

    // Middle index (0-based)
    std::size_t mid = words.size() / 2;

    // Remove the middle word
    words.erase(words.begin() + mid);

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

    return oss.str();
}

int main() {
    std::string s = "c c++ java rust python";
    
    std::cout << removeMiddleWord(s) << "\n";
}

 
   
/*
run:
   
c c++ rust python

*/

 



answered Dec 24, 2025 by avibootz
...