c++ Program to reverse the sentence
C++ Program to reverse the sentence
Input- "My name is Nikhil"
Output "Nikhil is name My"
Here the idea to reverse each word in 1st phase and in 2nd phase reverse the whole sentence.
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
getline(cin,s);
cout<<s<<endl;
int l=s.size();
int pre=0;
for(int i=0;i<l;i++)
{
if(s[i]==' ')
{
int k=i-1;
while(pre<k){char c=s[pre]; s[pre]=s[k]; s[k]=c; pre++; k--; }
pre=i+1;
}
else if(i==l-1)
{
int k=i;
while(pre<k){char c=s[pre]; s[pre]=s[k]; s[k]=c; pre++; k--; }
}
}
int bck=0;
int nxt=l-1;
while(bck<nxt)
{
char c=s[bck];
s[bck]=s[nxt];
s[nxt]=c;
nxt--; bck++;
}
cout<<s<<endl;
return 0;
}
Input- "My name is Nikhil"
Output "Nikhil is name My"
Here the idea to reverse each word in 1st phase and in 2nd phase reverse the whole sentence.
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
getline(cin,s);
cout<<s<<endl;
int l=s.size();
int pre=0;
for(int i=0;i<l;i++)
{
if(s[i]==' ')
{
int k=i-1;
while(pre<k){char c=s[pre]; s[pre]=s[k]; s[k]=c; pre++; k--; }
pre=i+1;
}
else if(i==l-1)
{
int k=i;
while(pre<k){char c=s[pre]; s[pre]=s[k]; s[k]=c; pre++; k--; }
}
}
int bck=0;
int nxt=l-1;
while(bck<nxt)
{
char c=s[bck];
s[bck]=s[nxt];
s[nxt]=c;
nxt--; bck++;
}
cout<<s<<endl;
return 0;
}
Comments
Post a Comment