题目描述
思路
用一个数组space保存字符串里所有空格的位置,方便计算,假设字符串开头位置之前和末尾位置之后都是空格,然后反向地根据空格位置输出单词,一定要注意输出格式!
代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
string word;
getline(cin,word);
int leng=word.length();
int space[82];
int j=1;
space[0]=-1;
for(int i=0;i<leng;i++)
{
if(word[i]==' ')
space[j++]=i;
}
space[j]=leng;
int start=space[j-1];
int end=space[j];
while(j>=0)
{
for(int i=start+1;i<end;i++)
cout<<word[i];
j--;
start=space[j-1];
end=space[j];
if(j>=1)
{
cout<<" ";
}
}
}