1009. 说反话 (20)
2015-11-23 14:09
405 查看
1009. 说反话 (20)
给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。
输入格式:测试输入包含一个测试用例,在一行内给出总长度不超过80的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用1个空格分开,输入保证句子末尾没有多余的空格。
输出格式:每个测试用例的输出占一行,输出倒序后的句子。
输入样例:
Hello World Here I Come
输出样例:
Come I Here World Hello
网上有推荐使用strtok函数,代码如下:
PS:几点补充
给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。
输入格式:测试输入包含一个测试用例,在一行内给出总长度不超过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。每次调用成功则返回被分割出片段的指针。
相关文章推荐
- 【Python】django权限管理
- python帮助信息查看以及笔记
- 如何把运行期警告转移到编译期的几个小技巧
- Eclipse安装SVN插件教程
- AndroidManifest.xml权限设置
- Vijos1647 不差钱
- 麦子学院cocos2d听课截图
- hdoj Co-prime 4135 (容斥原理)
- 根据文件名修改文件(创业天使-xxx 120101_超清.mp4 --> 120101-创业天使-xxx.mp4)
- spring框架学习(三)junit单元测试
- 10段代码打通js学习的任督二脉
- MySQL索引背后的数据结构及算法原理
- SQL SERVER如何通过SQL语句获服务器硬件和系统信息
- 单核CPU,多线程与性能
- Python基础之【第四篇】
- esc安装数据库 sqlserver mssql
- Android studio 使用问题汇总
- spring框架学习(二)依赖注入
- getReadableDatebase() 和getwriteableDatebase()
- Java的文件读写操作