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

51,811 answers

573 users

How to reverse the order of the words in a string with C++

2 Answers

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

void rtrim(std::string &s) {
    s.erase(find_if(s.rbegin(), s.rend(), [](int ch) {
        return !isspace(ch);
    }).base(), s.end());
}

std::string reverseOrderOfWordsInString(std::string &s) {
    std::vector <std::string> tokens; 
    std::stringstream sst(s); 
    std::string word; 
         
    while(getline(sst, word, ' ')) { 
        tokens.push_back(word); 
    } 
        
    reverse(tokens.begin(), tokens.end());
         
    s = "";
    for (int i = 0; i < tokens.size(); i++) {
        s += tokens[i] + " ";
    } 
 
    rtrim(s);
    
    return s;
}
 
int main()
{
    std::string s = "c++ c java php c#";
    
    s = reverseOrderOfWordsInString(s);
    
    std::cout << s;
}

  
/*
run:
 
c# php java c c++
 
*/

 



answered Dec 5, 2019 by avibootz
edited Jul 19, 2024 by avibootz
0 votes
#include <bits/stdc++.h> 
      
using namespace std;
 
void rtrim(string &s) {
    s.erase(find_if(s.rbegin(), s.rend(), [](int ch) {
        return !isspace(ch);
    }).base(), s.end());
}
 
void reverseOrderOfWordsInString(string &s) {
    vector <string> tokens; 
        
    stringstream sst(s); 
        
    string word; 
        
    while (getline(sst, word, ' ')) { 
        tokens.push_back(word); 
    } 
       
    reverse(tokens.begin(), tokens.end());
        
    s = "";
    for(int i = 0; i < tokens.size(); i++) {
        s += tokens[i] + " ";
    } 
     
    rtrim(s);
}
  
int main()
{
    string s = "c++ c java php c#";
     
    reverseOrderOfWordsInString(s);
     
    cout << s;
}
  
 
  
/*
run:
 
c# php java c c++
 
*/

 



answered Dec 5, 2019 by avibootz
edited Jul 19, 2024 by avibootz
...