题目:输入一个英文句子,翻转句子中单词的顺序,单词内字符的顺序不变。
句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。
例子:输入“I am a student.”,则输出“student.a am I”。
总体思想:根据字符串中的' '将切割出每一个单词,然后倒置顺序,最后将整个字符串倒置。
C++源码:
#include<iostream> #include<string> using namespace std; void words_reverse(string *words,int begin,int end)//单纯进行翻转 { while(begin<end) { char t=words->at(begin); words->at(begin)=words->at(end); words->at(end)=t; ++begin; --end; } } void string_reverse(string *s)//进行单词切割翻转 { int j=0; for(int i=0;i<s.length();i++) { if(s.at(i)==' ') { words_reverse(&s,j,i-1); j=i+1; } } } int main() { string s="I am a student."; string_reverse(&s); words_reverse(&s,j,s.length()-1);//最后一个单词交换顺序 words_reverse(&s,0,s.length()-1);//所有的交换顺序 /*words_reverse(&s,0,0); words_reverse(&s,2,3); words_reverse(&s,5,5); words_reverse(&s,7,14); words_reverse(&s,0,14);*/ cout<<s<<endl; }