PROBLEM
We wish to reverse the words of a sentence/phrase without using another array.
For example, I AM GOOD should become GOOD AM I.
STEPS
We will solve the given problem in two steps:
1. We will reverse the whole string.
DOOG MA I
2. We will reverse each word seperately.
GOOD AM I
PROGRAM
// Program to reverse the words in a given string (without using another array)
#include <iostream>
using namespace std;
int main()
{
string s;
int begin,end,i,j=0,len,temp,count=0;
cout<<"ENTER STRING: ";
getline(cin,s);
//To find the length of string
len=s.length();
//To reverse whole string
for(i=0;i<(len/2);i++)
{
temp=s[i];
s[i]=s[len-1-i];
s[len-1-i]=temp;
}
//To reverse each word seperately
for(i=0;i<len;i++)
{
if(s[i]==' ' || s[i]=='\0')
{
for(begin=j,end=i-1 ; begin<(i+j)/2 ; begin++,end--)
{
temp=s[begin];
s[begin]=s[end];
s[end]=temp;
}
j=i+1;
}
}
cout<<s<<" ";
return 0;
}
OUTPUT
We wish to reverse the words of a sentence/phrase without using another array.
For example, I AM GOOD should become GOOD AM I.
STEPS
We will solve the given problem in two steps:
1. We will reverse the whole string.
DOOG MA I
2. We will reverse each word seperately.
GOOD AM I
PROGRAM
// Program to reverse the words in a given string (without using another array)
#include <iostream>
using namespace std;
int main()
{
string s;
int begin,end,i,j=0,len,temp,count=0;
cout<<"ENTER STRING: ";
getline(cin,s);
//To find the length of string
len=s.length();
//To reverse whole string
for(i=0;i<(len/2);i++)
{
temp=s[i];
s[i]=s[len-1-i];
s[len-1-i]=temp;
}
//To reverse each word seperately
for(i=0;i<len;i++)
{
if(s[i]==' ' || s[i]=='\0')
{
for(begin=j,end=i-1 ; begin<(i+j)/2 ; begin++,end--)
{
temp=s[begin];
s[begin]=s[end];
s[end]=temp;
}
j=i+1;
}
}
cout<<s<<" ";
return 0;
}
OUTPUT
2 comments
comments//To reverse each word seperately
Replyfor(i=0; i<=len; i++)// 'i' must be less then equal to length, otherwise and will incorrect
for example string is : Ram go to school
While reversing each word separately you should take the limit as (len+1) for the very first loop.
ReplyInstead of I as first word try checking with two or more letter words and you would know why.