# Reverse Words in a String in C++

Suppose we have a string with few words. We have to reverse the word positions in the string. So if the string is like “The quick brown fox jumps over a lazy dog”

To solve this, we will follow these steps −

• Define a function getString(), this will take s as input, this will work as −

• i := 0, j := size of s – 1

• while s[i] = ‘ ’ and i < size of s, increase i by 1

• while j >= 0 and s[j] = ‘ ’, decrease j by 1

• ret := empty string

• for i <= j, increase i by 1

• if size of ret is non-zero and the last element of ret is ‘ ’ and s[i] is ‘ ’, then go for the next iteration

• ret := ret + s[i]

• Define another method called reverseWords(), this will take s as input

• j := 0

• for I in range 0 to the size of s – 1, in each step set i := j

• if s[i] is blank, then j := i + 1

• otherwise

• while j + 1 < size of s and s[j + 1] is not space, then increase j by 1

• x := i and y := j

• while x < y

• exchange s[x] and s[y], increase x by 1 and decease y by 1

• increase j by 1

• From the main method, do the following −

• reverse the string s

• reverseWords(s)

• return getString(s)

## Example (C++)

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string reverseWords(string s) {
reverse(s.begin(), s.end());
reverseWordss(s);
return getString(s);
}
string getString(string s){
int i = 0;
int j = s.size() - 1;
while(s[i] == ' ' && i < s.size()) i++;
while(j >= 0 && s[j] == ' ') j--;
string ret = "";
for(;i <= j; i++){
if(ret.size() && ret.back() == ' ' && s[i] == ' ')continue;
ret += s[i];
}
return ret;
}
void reverseWordss(string& s){
int j = 0;
for(int i = 0; i < s.size() ;i = j){
if(s[i] == ' '){
j = i + 1;
}
else{
while(j + 1 < s.size() && s[j + 1] != ' ') j++;
int x = i;
int y = j;
while(x < y){
swap(s[x], s[y]);
x++;
y--;
}
j++;
}
}
}
};
main(){
Solution ob;
cout << (ob.reverseWords("The quick brown fox jumps over a lazy dog"));
}

## Input

"The quick brown fox jumps over a lazy dog"

## Output

"dog lazy a over jumps fox brown quick The"

Updated on: 29-Apr-2020

5K+ Views