Reverse Each Word in a String
“Reverse Each Word in a String” is a popular problem of string data structure. Here, we are given a string of words and our task is to write a program to reverse each word in a 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 in a string is as follows:
- Create an empty character stack and initialize an empty resultant string.
- Start traversing a string.
- Push characters of the string in the stack until ‘space character’ appears.
- Once space character is appeared. Pop all characters from the stack and concatenate them with resultant string.
- Concatenate a ‘space character’ afterwards.
- Repeat steps from 3 to 5 until complete string is scanned.
- In last, concatenate the remaining word to resultant string from stack.
- Return the resultant string.
C++ Program to reverse each word in a string is as follows:
/* Program to reverse each word in a string */
#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:
- Program to Print All the Substring of the Given String.
- Program to find longest palindromic Substring.
- Program to check Anagram Strings.
- Program to check whether two Strings are Rotation of each other or not.
- Program to check Palindromic Anagram.
- Program to print all the Palindromic Substring of the String.
- Program to check Panagram String.
- Program to find first non-repeating character of the String.
- Program to Reverse a String.
- Program to Count Number of Characters in a String.
- Program to Count frequency of particular character of the String.
- Program to Count Number of Vowels and Number of Consonants in a String.
- Program to Check if String is alphabetic or numeric or alpha-numeric.
- Program to copy one String to Another.
- Program to Concatenate Two Strings.
- Program to Check whether given String is Palindrome or not.
- Program to convert lower-case alphabet to upper-case alphabet and vice-versa.
- Program to count total number of words in a string.
- Program to find smallest and largest word of the String.
- Program to print Alternate Elements of an Array.