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

51,922 answers

573 users

How to print the middle words of a string in C++

2 Answers

0 votes
#include <iostream> 
 
void printMiddleWords(std::string s) { 
    int i = 0; 
     
    for (i = 0; i < s.length() && s[i] != ' '; i++) ;
  
    std::string word = ""; 
    for (i++; i < s.length(); i++) { 
         if (s[i] != ' ') 
            word += s[i]; 
         else { 
            std::cout << word << " "; 
            word = ""; 
         } 
    } 
} 
    
int main() 
{ 
    std::string s = "c++ c java python rust"; 
      
    printMiddleWords(s); 
} 
  
  
  
/*
run:
  
c java python 
  
*/

 



answered Dec 5, 2019 by avibootz
edited Oct 7, 2024 by avibootz
0 votes
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

void printMiddleWords(const std::string& str) {
    std::vector<std::string> words;
    std::istringstream iss(str);
    std::string word;
    
    // Split the string into words
    while (iss >> word) {
        words.push_back(word);
    }
    
    int count = words.size();
    if (count % 2 == 0) {
        std::cout << "Middle words: " << words[count / 2 - 1] << " " << words[count / 2] << "\n";
    } else {
        std::cout << "Middle word: " << words[count / 2] << "\n";
    }
}

int main() {
    std::string str = "c++ c java python c# rust";
    
    printMiddleWords(str);
}

 
/*
run:
 
Middle words: java python
 
*/

 



answered Oct 7, 2024 by avibootz
...