1009. 说反话 (20)
给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。
输入格式:测试输入包含一个测试用例,在一行内给出总长度不超过80的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用1个空格分开,输入保证句子末尾没有多余的空格。
输出格式:每个测试用例的输出占一行,输出倒序后的句子。
输入样例:Hello World Here I Come
输出样例:
Come I Here World Hello
Answer:
#include<iostream>
#define MAX 81
using namespace std;
int main() {
char sentence[MAX];
cin.getline(sentence, MAX);
int end_index = 0;
while(sentence[end_index])
end_index ++;
end_index --;
for(int i = end_index; i > 0; i --) {
if(sentence[i] == ' ') {
for(int j = i + 1; j <= end_index; j ++) {
cout << sentence[j];
}
cout << ' ';
end_index = i - 1;
}
}
int i = sentence[0] == ' ' ? 1 : 0;
for(; i <= end_index; i ++)
cout << sentence[i];
}
PS.
这个问题也可以叫做“找空格”。