http://www.patest.cn/contests/pat-b-practise/1009
描述:
给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。
输入格式:测试输入包含一个测试用例,在一行内给出总长度不超过80的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用1个空格分开,输入保证句子末尾没有多余的空格。
输出格式:每个测试用例的输出占一行,输出倒序后的句子。
输入样例:Hello World Here I Come输出样例:
Come I Here World Hello虽然字符串遍历就能解决问题。可是一开始我尝试用库函数strtok来分割字符串,但并没有搞懂,望大牛不吝指导。
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
string res[100];
string str="";
getline(cin, str);
int index=0;//当前要添加的位置
bool flag=0;
string temp="";
for(int j=0 ; j<str.length() ; j++)
{
if ((str[j]==' ')&& flag==1)
{
res[index++]=temp;
temp="";
flag=0;
}
else{
flag=1;
temp+=str[j];
}
}
res[index++]=temp;
cout << res[index-1];
for(int i=index-2 ; i>=0 ; i--)
cout << " " <<res[i];
/*
//尝试用库函数分割
string strr="";
getline(cin, strr);
cout << strr << endl;
char* str;
strcpy(str,strr.c_str());
cout << str <<endl;
char *tokenPtr=strtok(str," ");
while(tokenPtr!=NULL) {
cout<<tokenPtr<<'\n';
tokenPtr=strtok(NULL," ");
}*/
return 0;
}