reverse words in a string , donot reverse word letters

Given an input string, reverse the string word by word.

For example,
Given s = “the sky is blue”,
return “blue is sky the”.

void reverseWords(string &s)
string word; //tmp string to store each word
string res; // result string
int i=0;
while (i<s.size()){
if (char(s[i])==’ ‘ && word.empty()){i++;continue;} //multiple spaces
if (char(s[i])==’ ‘ && !word.empty()){ //first space after a word
res = word+” “+ res; //store the word
word=””; //reset the word
i++; continue;
if (char(s[i])!=’ ‘){word=word+char(s[i]);i++; continue;} //non-space chars

if (!word.empty()){ //last word
s = word+” “+res;
s = res;
s = s.substr(0,s.size()-1); //eliminate the last space


Resolving technical problems:

Solve your technical problems instantly

We provide Remote Technical Support from Monday to Sunday, 7:00PM to 1:00 AM

Mail your problem details at along with your mobile numberand we will give you a call for further details. We usually attend your problems within 60 minutes and solve it in maximum 2 days.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.