Skip to main content

Reverse words in a given String

Task: Reverse the entire string without reverse individual words, which is consisting of words with separated by dots.

Example:
Input:
i.like.this.program.very.much
Output:
much.very.program.this.like.i

Here is the Code:
Program in C++:

  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. string reverseWords(string s)
  5. {
  6.     stack<char> st;
  7.     int c=0;
  8.     //reverse individual words
  9.     for(int i=0;i<s.length();i++)
  10.     {
  11.         if(s[i]=='.')
  12.         {
  13.             //back to starting position
  14.             //of current word
  15.             i=i-c;
  16.             while(st.empty()==false)
  17.             {
  18.                 s[i]=st.top();
  19.                 st.pop();
  20.                 i++;
  21.             }
  22.             c=0;
  23.         }
  24.         else
  25.         {
  26.             st.push(s[i]);
  27.             c++;
  28.         }
  29.     }
  30.     int i = s.length()-c;
  31.     while(st.empty()==false)
  32.     {
  33.         s[i]=st.top();
  34.         st.pop();
  35.         i++;
  36.     }
  37.     //reverse entire string
  38.     for(int i=0;i<s.length();i++)
  39.     {
  40.         st.push(s[i]);
  41.     }
  42.     i=0;
  43.     while(st.empty()==false)
  44.     {
  45.         s[i]=st.top();
  46.         st.pop();
  47.         i++;
  48.     }
  49.     return s;
  50. }
  51. int main()
  52.  {
  53.     //Number of test cases
  54. int t;
  55. scanf("%d\n",&t);
  56. string s;
  57. while(t--)
  58. {
  59.     getline(cin, s);
  60.     cout<<reverseWords(s)<<endl;
  61. }
  62. return 0;
  63. }

Here is the Video: