您的位置:首页 > 其它

1009. 说反话 (20)

2015-11-23 14:09 405 查看
1009. 说反话 (20)

给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。

输入格式:测试输入包含一个测试用例,在一行内给出总长度不超过80的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用1个空格分开,输入保证句子末尾没有多余的空格。

输出格式:每个测试用例的输出占一行,输出倒序后的句子。

输入样例:

Hello World Here I Come

输出样例:

Come I Here World Hello

#include<iostream>
#include<vector>
#include<fstream>
#include<string>
using namespace std;
int main()
{
fstream file("data.txt");
string data;
if(!file.fail())
{
getline(file,data);
cout<<data<<endl;
}
int pos=0;
int pos1=0;
vector<string> words;
while(pos1!=string::npos)
{
pos1=data.find_first_of(" ",pos);
if(pos1!=string::npos)
{
string word=data.substr(pos,pos1-pos);
pos=pos1+1;
words.push_back(word);
}
else
{
string word=data.substr(pos,data.length()-pos);
pos=pos1+1;
words.push_back(word);
}
}

for(vector<string>::iterator it=words.end();it!=(words.begin()+1);it--)
{
cout<<*(it-1)<<" ";
}
cout<<words[0]<<endl;
return 0;
}


网上有推荐使用strtok函数,代码如下:

#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
int main()
{
fstream file("data.txt");
string data;
char ptr[80];
char* word;
vector<string> words;
if(!file.fail())
{
getline(file,data);
strcpy(ptr,data.c_str());
}
cout<<ptr<<endl;
word=strtok(ptr," ");
while(word!=NULL)
{
words.push_back(word);
word=strtok(NULL," ");
}
for(vector<string>::iterator it=words.end();it!=(words.begin()+1);it--)
{
cout<<*(it-1)<<" ";
}
cout<<words[0]<<endl;
return 0;
}


PS:几点补充

getline(file,data);
strcpy(ptr,data.c_str());//将string转换为char*


word=strtok(ptr," ");
while(word!=NULL)
{
words.push_back(word);
word=strtok(NULL," ");
}


函数原型:char *strtok(char *s, const char *delim);
Function:分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。
Description:strtok()用来将字符串分割成一个个片段。参数s指向欲分割的字符串,参数delim则为分割字符串,当strtok()在参数s的字符串中发现到参数delim的分割字符时      则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回被分割出片段的指针。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: