Reversing words in an input text stream

Program Description

This program is an example to show how you can process text in C++.
This program reverses individual words in an input text stream.
eg:
Input: This is an example text
Output: sihT si na elpmaxe txet

The program uses standard template library's(STL) "stack" data structure.

Program
/********************************************
*	 code.cheraus.com
*
*     Reversing words in an input text stream
*
********************************************/



#include<iostream>
#include<cstring>
#include<stack>
using namespace std;

class st{
 private:
       char str[250];
 public:
       void getdata();
       void display();
       void convert();
       void reverse(int start,int end);

};
void st::getdata()
{
  cout<<"\nEnter the String : ";
  cin.getline(str,250);
}
void st::display()
{
  cout<<str;
}
void st::convert()
{
  int len=0,i=0,j=1,k=0,space[100];
 // stack<char> temp;
  len = strlen(str);
 // cout<<len<<"\n";
   space[0]=-1;
   for(i=0;i<len;i++)
   {
     if(str[i]==32)
     {
       space[j++] = i;
     }
   }
    space[j] = len;
    for(i=0;i<j;i++)
     {
       reverse(space[i],space[i+1]);
     }
}
void st::reverse(int start,int end)
{
  stack<char> temp;
  int i=0;
  for(i=start+1;i<end;i++)
   {
      temp.push(str[i]);
   }
  for(i=start+1;i<end;i++)
   {
      str[i] = temp.top();
      temp.pop();
   }
}
int main()
{
   st a;
   a.getdata();
   cout<<"\nThe string you Entered is : ";
   a.display();
   cout<<"\nThe string after reverse : ";
   a.convert();
   a.display();
   cout<<"\n";
   return 0;
}

Output
Test Case 1:

Enter the String : This is a test example

The string you Entered is : This is a test example
The string after reverse : sihT si a tset elpmaxe

Test Case 2:

Enter the String : Welcome to code.cheraus

The string you Entered is : Welcome to code.cheraus
The string after reverse : emocleW ot suarehc.edoc

Test Case 3:

Enter the String : Hello World

The string you Entered is : Hello World
The string after reverse : olleH dlroW

Comments
comments powered by Disqus