Reverse Each Word of the String

Reverse Each Word of the String” is a popular problem of string data structure asked in many technical interviews. Here, we are given a string of words and Our task is to reverse each word of the string.

Example:

```INPUT:
HelpMeStudyBro is an Emerging Website
OUTPUT:
orBydutSeMpleH si na gnigremE etisbeW ```

This problem can be easily solved using stack. The steps required to reverse each word of the string is as follows:

1. Create an empty character stack and initialize an empty resultant string.
2. Start traversing a string.
3. Push all the characters of the string in the stack until ‘space character’ appears.
4. Once space character is appeared.  Pop all characters from the stack and concatenate them with resultant string.
5. Concatenate a ‘space character’ afterwards.
6. Repeat steps from 3 to 5 until complete string is scanned.
7. In last concatenate the remaining word to resultant string from stack.
8. Return the resultant string.

C++ Program to reverse each word of the string is as follows:

```#include<bits/stdc++.h>
using namespace std;
string reverseWords(string str)
{
stack<char>st;
string res = "";
for(int i = 0 ; i < str.length() ; i++)
{
// Push the complete word in the string
if(str[i] != ' ')
{
st.push(str[i]);
}
else
{
// reverse the word and concatneate to resultant string
while(!st.empty())
{

char ch = st.top();
res=res+ch;
st.pop();
}
res=res+" ";
}
}
// concatenate the last reversed word to string
while(!st.empty())
{
char ch = st.top();
res=res+ch;
st.pop();
}
return res;
}
int main()
{
string str;
cout<<"Enter a string: ";
getline(cin,str);
string res = reverseWords(str);
cout<<"\nResultant string:\n"<<res<<"\n";
}

```
```OUTPUT:
Enter a string:
HelpMeStudyBro is an Emerging Website
Resultant string:
orBydutSeMpleH si na gnigremE etisbeW```

Related Posts: