题目:句子逆序
将一个英文句子一单词为单位逆序排行。例如”I am a boy”,逆序排放后为“boy a am I”。所有单词之间用一个空格隔开,语句中除了英文单词外,不再包含其他字符。
方法一:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
void RS(char* begin,char *end)
{
while(begin<end)
{
char temp=*begin;
*begin=*end;
*end=temp;
begin++;
end--;
}
}
void Reverse(char *s)
{
int len=strlen(s);
RS(s,s+len-1);
char *p1,*p2;
p1=p2=s;
while(*p2 != '\0')
{
while(*p2!='\0' && *p2 != ' ')
{
p2++;
}
RS(p1,p2-1);
if(*p2== ' '&*p2 !='\0')
{
p2++;
p1=p2;
}
}
}
int main()
{
char str[1000];
gets(str);
Reverse(str);
char *p=str;
while(*p!='\0')
{
cout<<*p;
p++;
}
}
方法二:用STL实现
#include<iostream>
#include<vector>
#include<string>
#include<sstream>
#include<algorithm>
using namespace std;
int main()
{
string line,word;
vector<string> vs;
getline(cin,line);
istringstream ss(line);
while(ss>>word)
vs.push_back(word);
reverse(vs.begin(),vs.end());
vector<string>::const_iterator it=vs.begin();
for(;it!=vs.end();++it)
cout<<*it<<" ";
return 0;
}