本次讲一下倒叙输出句子的简单算法,倒序输出有很多种方式,其中一种是给出一个句子,由空格和单词组成,请给出算法,倒序输出。
本题相对简单,基本算法就是根据提示只有空格和单词,纳闷我们就可以以空格为边界,具体取后面的单词来实现倒序输出。具体code如下:由code可以看出,基本逻辑就是for循环根据空格取子串的操作。
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
while(getline(cin,str))
{
int pos=str.length()-1;
cout<<pos <<endl;
for(int i=pos;i>0;i--)
{
if(str[i]==' ')
{
cout<<str.substr((i+1),(pos-i))<<' ';
pos=i-1;
}
}
cout<<str.substr(0,pos+1)<<endl;
}
return 0;
}