题目地址:https://pintia.cn/problem-sets/994805260223102976/problems/994805314941992960ios
给定一句英语,要求你编写程序,将句中全部单词的顺序颠倒输出。函数
测试输入包含一个测试用例,在一行内给出总长度不超过 80 的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用 1 个空格分开,输入保证句子末尾没有多余的空格。测试
每一个测试用例的输出占一行,输出倒序后的句子。spa
Hello World Here I Come
Come I Here World Hello
从后往前,每遇到一个空格,输出这个空格以后的一个单词,而后更改单词尾的位置。在遍历一遍以后,由于第一个单词以前没有空格,因此剩余第一个单词未输出,输出第一个单词便可。code
#include<iostream> //#include<string> #include<string.h> using namespace std; int main() { // #include<string> 中的函数 // string words; // getline(cin, words); char words[80]; // #include<string.h> 中的函数 // 第二位参数表明容许输入的字符个数,小于,不会等于 ,例如81 只能输入80个字符 cin.getline(words, 81); int length = strlen(words); int indexA = length - 1; int indexZ = length; for ( ; indexA >= 0; indexA--) { if (words[indexA] == ' ') { for (int index = indexA + 1; index < indexZ; index++) { cout << words[index]; } cout << ' '; indexZ = indexA; } } // 循环结束后,indexA 等于 -1; // 剩余第一个单词未输出 for (indexA++; indexA < indexZ; indexA++) { cout << words[indexA]; } return 0; }