Reverse words in a given string
PROBLEM :
Given a String of length N reverse the words 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 spaces and characters.
Output:
For each test case, output a single line containing the reversed String.
Constraints:
1<=T<=10
1<=Lenght of String<=2000
Example:
Input:
2
i.like.this.program.very.much
pqr.mno
Output:
much.very.program.this.like.i
mno.pqr
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
#include<malloc.h>
void Reverse_words(char *) ;
void reverse(char *,char *) ;
int main()
{
int t ;
char *str ;
str=(char*)malloc(1000*sizeof(char)) ;
cin>>t ;
while(t--)
{
cin>>str ;
Reverse_words(str) ;
cout<<str<<endl ;
}
return 0;
}
void Reverse_words(char *str)
{
char *temp,*begin ;
temp=str ;
begin=str ;
while(*temp!='\0')
{
temp++ ;
if((*temp)=='\0')
{
reverse(begin,temp-1) ;
}
else if((*temp)=='.')
{
reverse(begin,temp-1) ;
begin=temp+1 ;
}
}
reverse(str,temp-1) ;
}
void reverse(char *start,char *end)
{
char temp ;
while(start<end)
{
temp=(*start) ;
(*start)=(*end) ;
(*end)=temp ;
start++ ;
end--;
}
}
---------------------------------------------------------------------------------
Given a String of length N reverse the words 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 spaces and characters.
Output:
For each test case, output a single line containing the reversed String.
Constraints:
1<=T<=10
1<=Lenght of String<=2000
Example:
Input:
2
i.like.this.program.very.much
pqr.mno
Output:
much.very.program.this.like.i
mno.pqr
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
#include<malloc.h>
void Reverse_words(char *) ;
void reverse(char *,char *) ;
int main()
{
int t ;
char *str ;
str=(char*)malloc(1000*sizeof(char)) ;
cin>>t ;
while(t--)
{
cin>>str ;
Reverse_words(str) ;
cout<<str<<endl ;
}
return 0;
}
void Reverse_words(char *str)
{
char *temp,*begin ;
temp=str ;
begin=str ;
while(*temp!='\0')
{
temp++ ;
if((*temp)=='\0')
{
reverse(begin,temp-1) ;
}
else if((*temp)=='.')
{
reverse(begin,temp-1) ;
begin=temp+1 ;
}
}
reverse(str,temp-1) ;
}
void reverse(char *start,char *end)
{
char temp ;
while(start<end)
{
temp=(*start) ;
(*start)=(*end) ;
(*end)=temp ;
start++ ;
end--;
}
}
---------------------------------------------------------------------------------
Comments
Post a Comment