Reverse each word in a given string

PROBLEM :
Given a String of length N reverse each word in it. Words are separated by dots.

Input:
The first line contains T denoting the number of testcases. Then follows description of testcases. Each case contains a string containing dots and characters.

Output:
For each test case, output a String in single line containing the reversed words of the given String.

Constraints:
1<=T<=10
1<=Length of String<=2000

Example:
Input:
2
i.like.this.program.very.much
pqr.mno

Output:
i.ekil.siht.margorp.yrev.hcum
rqp.onm

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
#include<string.h>
string Reverse_each_word(string ) ;
string reverse(string ,int ,int ) ;
int main()
 {
int t ;
string str ;
cin>>t ;
while(t--)
{
   cin>>str ;
   cout<<Reverse_each_word(str)<<endl ;
}
return 0;
}

string Reverse_each_word(string str)
{
    int start,len,i ;
    len=str.length() ;
    start=0 ;
   
    for(i=0;i<len;i++)
    {
        if(str[i]=='.')
        {
            str=reverse(str,start,i-1) ;
            start=i+1 ;
        }
    }
    str=reverse(str,start,i-1) ;
    return str ;
}

string reverse(string str,int start,int end)
{
    if(start>=end)
        return str ;
       
    char temp ;
    while(start<end)
    {
        temp=str[start] ;
        str[start]=str[end] ;
        str[end]=temp ;
       
        start++ ;
        end-- ;
    }
    return str ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )